How to set the Stack Name of a CDK Deployment

avatar

Borislav Hadzhiev

Fri Apr 23 20211 min read

banner

Photo by Timothy Muza

Updated on Fri Apr 23 2021

Explicitly setting the Stack Name in AWS CDK #

In order to explicitly set the stack name in CDK we have to provide the stackName prop when creating the Stack.

const app = new cdk.App(); new MyCdkStack(app, 'my-construct-id', { // ๐Ÿ‘‡ explicitly setting stack name stackName: `my-cdk-stack`, });

For Python users - the property is named stack_name, instead of stackName.

If we now deploy our stack by running npx cdk deploy, the name is set to my-cdk-stack:

with stack name

Accessing the Stack Name in AWS CDK #

In order to get the name of a CDK Stack we have to access the stackName property on the Stack class.

export class MyCdkStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); console.log('stackName ๐Ÿ‘‰ ', cdk.Stack.of(this).stackName); } }

The output from the console.log call shows the stack name:

cdk stack name

Default Behavior Without setting Stack Name #

The default behavior is that if we deploy a stack without providing the stackName property, CDK sets the stack name to be inferred to the construct id of the stack.

const app = new cdk.App(); new MyCdkStack(app, 'my-construct-id');

In the above scenario our stack will be named my-construct-id.

without stack name

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