Sub topic 9
Choosing the target account and region
An environment in the CDK is the pair of an AWS account and a Region that a stack deploys into. This chapter assumes you can already define a stack with a bucket and a function, and that you have used cdk synth and cdk deploy with configured AWS credentials. Here you will learn how a stack gets its environment, what changes between an environment-agnostic and an environment-specific stack, and which errors to expect.
What an environment is
Every stack belongs to one account and one Region. CloudFormation cannot create a single stack that spans two Regions. If your app needs resources in us-east-1 and eu-west-1, it needs at least two stacks.
You set the environment with the env property on a stack. It takes an account and a region. You can leave either or both unset, and the CDK treats the stack differently depending on what you give it.
| Setting | Meaning | Template contents |
|---|---|---|
| `env` omitted | Environment-agnostic. The stack can deploy anywhere. | Account and Region appear as pseudo parameters resolved by CloudFormation |
| `env` with explicit values | Environment-specific. The stack targets one place. | Concrete account ID and Region are known at synthesis |
| `env` from `CDK_DEFAULT_*` | Environment-specific, taken from your CLI setup. | Concrete values, resolved when you run the CLI |
Three ways to set `env`
The first way is to hard-code the values. This is explicit and reviewable, and it makes the target clear from the code alone.
import * as cdk from 'aws-cdk-lib';
import { AppStack } from '../lib/app-stack';
const app = new cdk.App();
new AppStack(app, 'AppStack-Prod', {
env: { account: '123456789012', region: 'us-east-1' },
});The second way is to read the values the CLI resolved for you. When you run a command, the CLI looks at your credentials and profile, then sets the environment variables CDK_DEFAULT_ACCOUNT and CDK_DEFAULT_REGION for your app. The account comes from the credentials in use. The Region comes from the profile configuration or AWS_REGION. This lets the same code follow whichever profile you select.
import * as cdk from 'aws-cdk-lib';
import { AppStack } from '../lib/app-stack';
const app = new cdk.App();
new AppStack(app, 'AppStack-Dev', {
env: {
account: process.env.CDK_DEFAULT_ACCOUNT,
region: process.env.CDK_DEFAULT_REGION,
},
});The third way is to omit env. The stack is then environment-agnostic.
import aws_cdk as cdk
from app_stack import AppStack
app = cdk.App()
# No env: the template can be deployed to any account and Region.
AppStack(app, "AppStack-Agnostic")
app.synth()The Python version assumes your stack class lives in app_stack.py, as in the earlier chapters.
You can select a profile at deploy time with cdk deploy --profile prod. With the CDK_DEFAULT_* approach, that flag changes the environment the stack targets.
Environment-agnostic or environment-specific
Agnostic stacks sound flexible, but they cost you features. The CDK cannot know the account or Region while synthesizing, so anything that needs a real value fails or falls back to a looser form.
- Context lookups do not work. Methods such as
ec2.Vpc.fromLookupandroute53.HostedZone.fromLookupask AWS for information at synthesis time and cache the answer incdk.context.json. Without an account and Region, there is nothing to query. - Availability zones cannot be listed. An agnostic stack gets a CloudFormation
Fn::GetAZsexpression and typically two zones. A specific stack gets the real zone names. - Region-dependent logic cannot run at synthesis time. A check such as
stack.region === 'us-east-1'compares against a token, not a string, so it never behaves as you expect.
Use an agnostic stack only when you truly want one template for many places, for example a stack that you publish for others. For most application work, make the environment explicit.
import * as cdk from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import { Construct } from 'constructs';
export class NetworkLookupStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// Needs a concrete account and Region on the stack.
const vpc = ec2.Vpc.fromLookup(this, 'DefaultVpc', { isDefault: true });
new cdk.CfnOutput(this, 'VpcId', { value: vpc.vpcId });
}
}If you instantiate this stack without env, synthesis fails with an error saying the context provider cannot retrieve a value because the account or Region is not specified. The fix is to pass env.
Deploying one app to several environments
Because an environment belongs to a stack, one app can contain several stacks aimed at different places. The following example builds the same stack class for two environments, using stack IDs that identify each target.
import * as cdk from 'aws-cdk-lib';
import { AppStack } from '../lib/app-stack';
const app = new cdk.App();
const targets = [
{ name: 'Staging', account: '111111111111', region: 'eu-west-1' },
{ name: 'Prod', account: '222222222222', region: 'us-east-1' },
];
for (const t of targets) {
new AppStack(app, `AppStack-${t.name}`, {
env: { account: t.account, region: t.region },
});
}List the stacks with cdk list, then deploy one by name, for example cdk deploy AppStack-Staging. Deploying without a name works only when the app has a single stack. With several stacks, name the ones you want or pass --all.
Cross-environment effects
Choosing an environment has consequences beyond the stack itself.
- Bootstrapping is per environment. Each account and Region pair you deploy to needs its own bootstrap stack. The
cdk bootstrap aws://ACCOUNT/REGIONcommand from the setup chapter takes exactly the values you set here. If you forget,cdk deployreports that the environment has not been bootstrapped. - Stacks in different Regions cannot reference each other's values directly. A cross-Region reference needs
crossRegionReferences: trueon the stacks involved, which uses custom resources to pass values. Later chapters on cross-stack references cover this. - Credentials must reach every target. When your app targets several accounts, the CLI needs credentials that can use each account's bootstrap roles. The simplest approach is to start from credentials in a central account that the bootstrap trust allows.
Common errors
- Using
process.env.CDK_DEFAULT_ACCOUNTin code that you run with plainnodeor a test runner. The variables exist only when the CDK CLI launches the app, so they areundefinedelsewhere and the stack silently becomes agnostic. - Calling
fromLookupon an agnostic stack, which fails as described above. - Deploying to a Region that was never bootstrapped, even though the account was.
- Changing the
envof an existing stack and expecting CloudFormation to move it. A stack cannot move. The CDK treats the new environment as a separate deployment, so the old stack stays in place until you destroy it.
Exercise
A teammate writes new AppStack(app, 'Web') with no env and then calls ec2.Vpc.fromLookup(this, 'Vpc', { isDefault: true }) inside the stack. Synthesis fails. What is the cause, and what is the smallest change that fixes it?
Show answer
Without env, the stack is environment-agnostic, so the CDK has no account or Region to query when it performs the lookup. Pass an environment, for example env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION }, so the stack is environment-specific. Also make sure that environment has been bootstrapped before deploying.