Managing deployments across multiple AWS accounts often comes with credential headaches - constantly switching profiles, forgetting --aws-profile
, or accidentally deploying to the wrong environment. In this post, I’ll show you how to streamline the process by mapping stages to AWS CLI profiles directly in your serverless.yml
, making deployments pain-free and consistent.
⚙️ Why This Approach Matters
- No more CLI flags: Skip
--aws-profile
on every command, just use--stage
and you're done. - Safer workflows: Avoid accidentally deploying to production from your dev environment.
- Reusable pattern: Set it once, add new environments in seconds, ideal for scaling teams and CI/CD pipelines.
✅ Prerequisites
- Multiple AWS CLI profiles set up, each targeting the intended AWS account:
aws configure --profile dev aws configure --profile prod
- Serverless Framework CLI installed:
npm install -g serverless sls create --template aws-nodejs
🧩 Configure serverless.yml
Step 1: Map deployment stages to profiles
custom: profiles: dev: dev prod: prod test: test
Step 2: Use dynamic interpolation for provider.profile
provider: name: aws runtime: nodejs18.x region: ap-south-1 stage: ${opt:stage, 'dev'} profile: ${self:custom.profiles.${self:provider.stage}}
-
${opt:stage, 'dev'}
uses CLI--stage
, defaulting todev
. -
${...custom.profiles...}
fetches the matching AWS profile. - The result? No more need to type
--aws-profile
.
🔍 Full Example
service: multi-account-service frameworkVersion: '~4.4.0' custom: profiles: dev: dev prod: prod test: test provider: name: aws runtime: nodejs18.x region: ap-south-1 stage: ${opt:stage, 'dev'} profile: ${self:custom.profiles.${self:provider.stage}} functions: handler: handler: handler.main events: - httpApi: path: / method: ANY
🛠 Deploying Is Simple
sls deploy # → uses profile "dev" sls deploy --stage prod # → uses "prod" sls deploy --stage test # → uses "test"
💡 Best Practices
- Keep credentials private: Never commit them to Git.
- CI/CD-friendly: Define
AWS_PROFILE
via environment variables or secrets. - Team guidance Document the mapping in your README for clarity.
- Easily extendable Add more stages like
staging
,qa
, oruat
as you grow.
📝 Next Steps
This pattern is live in our projects, and it’s saved us from accidental deployments and excessive CLI flags. Give it a go in your own project, and if it works for you, let me know! I’m planning to follow up with posts on CI/CD pipelines, credentials rotation, and advanced Serverless best practices.
Top comments (0)