Never deploy AWS CDK Stacks in wrong account again

megaproaktiv

Gernot Glawe

Posted on June 15, 2021

Never deploy AWS CDK Stacks in wrong account again

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"            
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 },
});
Enter fullscreen mode Exit fullscreen mode

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"       
Enter fullscreen mode Exit fullscreen mode

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/#/

💖 💪 🙅 🚩
megaproaktiv
Gernot Glawe

Posted on June 15, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024

Modern C++ for LeetCode 🧑‍💻🚀
leetcode Modern C++ for LeetCode 🧑‍💻🚀

November 29, 2024