How to get Stack Name in AWS CDK

avatar

Borislav Hadzhiev

Sat Apr 24 20212 min read

Updated on Sat Apr 24 2021

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/core'; 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');

In the code snippet, we have 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 execute the CDK code by running the synth command:

shell
npx 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.

In the code snippet above, 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 like so:

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 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/core'; 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 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 #

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