How to set the Stack Name of a CDK Deployment

avatar

Borislav Hadzhiev

Last updated: Apr 13, 2022

banner

Check out my new book

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.

import * as cdk from 'aws-cdk-lib'; 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 aws-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.

import * as cdk from 'aws-cdk-lib'; 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 scenario above, our stack will be named my-construct-id.

without stack name

Further Reading #

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