How to get Stack Name in AWS CDK

avatar

Borislav Hadzhiev

Thu Apr 14 20222 min read

Updated - Thu Apr 14 2022

Getting the Stack Name in AWS CDK #

In order to get the name of a stack in CDK we have to access the stackName property on the core Stack class:

The code for this article is available on GitHub
lib/cdk-starter-stack.ts
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); } } const app = new cdk.App(); new MyCdkStack(app, 'my-cdk-stack');

We accessed the stackName property on the Stack class.

The Stack.of static method returns the Stack object, within which a construct is defined. The method provides a clean way to get a hold of the Stack object.

I'll run the CDK code by issuing the synth command:

shell
npx aws-cdk synth

The output shows that we've successfully retrieved the stack name:

synth class name

CDK resolves the stackName property on the Stack class at synthesis time, so we are able to access it in our code.

We didn't provide the stackName prop when instantiating our Stack, so the stack name was inferred from the id prop we passed to the Stack constructor.

We can explicitly set the stack name in the following way:

bin/cdk-starter.ts
const app = new cdk.App(); new MyCdkStack(app, 'my-cdk-id', { // 👇 explicitly set stackName prop stackName: 'explicit-stack-name', });

I'll now run the synth command to see the output from the console.log call:

shell
npx aws-cdk synth

The output shows that we've successfully overridden the stack name:

new stack name

Accessing the AWS::StackName Parameter #

If you need to access the AWS::StackName pseudo parameter from CloudFormation, you can use Aws.STACK_NAME:

lib/cdk-starter-stack.ts
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 param 👉', cdk.Aws.STACK_NAME); } }

I'll synth to see the output from the console.log call:

shell
npx aws-cdk synth

The STACK_NAME property on the Aws class resolves at deployment time, rather than at synthesis time, so we get a Token value:

aws stack name

Tokens in CDK are encoded values that get resolved by CloudFormation at deployment time. I've written an article on the topic - What is a Token in AWS CDK

Further Reading #

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