Never deploy AWS CDK Stacks in wrong account again
Gernot Glawe
Posted on June 15, 2021
Working for different customers and of cause in different accounts for lets say development and production, it is vital not to deploy in the wrong account!
Taskfile
This tool (taskfile.dev) allows preconditions for executing tasks.
deploy-prod:
desc: deploy Lambda
cmds:
- export CDK_DEFAULT_ACCOUNT={{.account}} && npx cdk@{{.version}} deploy reporting
preconditions:
- sh: "[ '{{.account}}' = '{{.accountprod}}' ]"
msg: "Account not prod, Halting"
Where
deploy-prod
- the Name of the Task
desc
- ription
cmds
- commands
{{.account}}
- a variable
preconditions
- only run this task if true
Thats good, but how do I get the account number?
You get the current account number with the STS simple/secure token services from aws. In the response, you query only the Account number, so
aws sts get-caller-identity --query Account --output text
Gives you the account number of the current credentials.
For the CDK, you tell it with
new LambdaStack(app, 'lambda', {
env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION },
});
To use the environment for account and region.
All together in the Taskfile
# https://taskfile.dev
version: '3'
env:
CDK_DEFAULT_REGION: eu-west-1
vars:
region: eu-west-1
account:
sh: aws sts get-caller-identity --query Account --output text
accountdev:
accounttest:
accountprod: 555555555555
# CDK Version
version: v2.0.0-rc.7
tasks:
deploy-prod:
desc: deploy Lambda/Reporting Stack
cmds:
- export CDK_DEFAULT_ACCOUNT={{.account}} && npx cdk@{{.version}} deploy reporting
preconditions:
- sh: "[ '{{.account}}' = '{{.accountprod}}' ]"
msg: "Account nicht prod, Halting"
With this setup, task deploy-prod
will only deploy on the configured prod account!
Hope you find this helpful,
Please contact me on twitter @megaproaktiv or discuss here aber life, universe and AWS devops.
Thanks
Photo by Tim Mossholder on Unsplash
Amazing tool https://taskfile.dev/#/
Posted on June 15, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.