How to set Region and Account for a CDK Deployment

avatar

Borislav Hadzhiev

Fri Apr 23 20212 min read

banner

Photo by Caleb Jones

Updated on Fri Apr 23 2021

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

Add me on LinkedIn

I'm a Web Developer with TypeScript, React.js, Node.js and AWS experience.

Let's connect on LinkedIn

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee