Borislav Hadzhiev
Reading timeยท2 min
Photo from Unsplash
In order to get the name of a stack in CDK we have to access the stackName property on the core 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); } } 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:
npx aws-cdk synth
The output shows that we've successfully retrieved the stack 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:
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:
npx aws-cdk synth
The output shows that we've successfully overridden the stack name:
If you need to access the
AWS::StackName
pseudo parameter from CloudFormation, you can use Aws.STACK_NAME
:
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:
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:
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