How to set Region and Account for a CDK Deployment

avatar

Borislav Hadzhiev

Wed Apr 13 20222 min read

banner

Photo by Caleb Jones

Updated - Wed Apr 13 2022

Setting Region and Account for a CDK Deployment #

In order to set the account and region of a CDK deployment, we have to explicitly set the env property when instantiating the stack.

const app = new cdk.App(); new MyCdkStack(app, `my-cdk-stack`, { stackName: `my-cdk-stack`, // 👇 Explicitly set env property env: { region: 'us-east-1', account: 123456789, }, });

We can set the values of region and account using explicitly set by us environment variables, secrets, parameters, etc.

An alternative approach would be to use environment variables that are already pre-set in the CDK environment:

const app = new cdk.App(); new MyCdkStack(app, `my-cdk-stack`, { stackName: `my-cdk-stack`, env: { region: process.env.CDK_DEFAULT_REGION, account: process.env.CDK_DEFAULT_ACCOUNT, }, });

The CDK_DEFAULT_REGION and CDK_DEFAULT_ACCOUNT environment variables get resolved based on the --profile flag we pass when deploying.

If we don't explicitly pass a --profile flag, then the values resolve to the account and region that correspond to our default AWS profile on that machine.

It's best practice to explicitly set concrete values for CDK_DEFAULT_REGION and CDK_DEFAULT_ACCOUNT because when collaborating with other developers on a project, we can't rely on every developer having the same settings for their default AWS profile. What ends up happening is the stack gets deployed to different regions/accounts by multiple people.

Environment Agnostic CDK Stacks #

The default behavior when we don't specify account and region is that the stack we deploy is environment agnostic.

This means that CDK CLI checks whether we passed in the --profile flag when deploying. If we did, it uses the account and region that correspond to that profile:

shell
npx aws-cdk deploy --profile myprofile my-stack

If we don't pass the --profile flag, CDK takes the account and region properties from the default profile on that machine:

shell
npx aws-cdk deploy my-stack

When we deploy an environment agnostic stack, we're unable to access the resolved values of the account and region properties because they get resolved at deployment time rather than synthesis time.

In order to explicitly set the account and region properties when deploying a CDK application we have to set the env property when initializing the stack.

const app = new cdk.App(); new MyCdkStack(app, `cdk-stack`, { stackName: `cdk-stack`, // 👇 explicitly setting env env: { region: 'us-east-1', account: 123456789, }, });

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.