I have a CDK app in typescript to deploy AWS resources for a specific project. I have multiple AWS accounts for different companies. I would usually do the following before running any CDK command:
export AWS_PROFILE=profile1
This would then let me run cdk deploy onto the profile1 account. Should I switch to work on another project that requires profile2, I would run:
export AWS_PROFILE=profile2
and continue.
This works but it's a little dangerous if I ever forget to run the export command.
I wonder if in the CDK typescript app, there is a way to specify the AWS profile for that project so any commands would implicitly use that profile so I do not have to remember to do it.
Any ideas?
You can set the account ID on each stack explicitly via its env prop:
new MyStack(app, 'MyStack', { env: { account: '111222333444', }, });
You can also create multiple stacks in the scope of a Stage, and set the account ID there:
const dev = new Stage(app, 'DevStage', { env: { account: '111222333444', }, });
new MyStack(dev, 'MyStack'); // will always be deployed to the Stage's account
Keep in mind that this will mean your stacks will be environment-specific. That means that the resulting CloudFormation template will include the environment (account ID) and will not be able to be deployed to a different environment.
NB: the latter solution will lead to a change in logical IDs of all resources.
If you go with stages, you can create your own subclass and create your stacks inside of it:
export class MyAppStage extends cdk.Stage {
constructor(scope: Construct, id: string, props?: cdk.StageProps) {
super(scope, id, props);
// create all your stacks inside the stage
new MyStack(this, 'MyStack');
// add more stacks as needed
// new AnotherStack(this, 'AnotherStack');
}
}
Then you can use multiple instances of your stage class to define multiple environments:
const devStage = new MyAppStage(app, 'DevStage', {
env: {
account: '111222333444',
region: 'us-east-1'
}
});
const prodStage = new MyAppStage(app, 'ProdStage', {
env: {
account: '555666777888',
region: 'us-east-1'
}
});
You would then deploy what you want with cdk deploy DevStage