Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CDK - How to get stack name in construct

I wrote a stack in CDK, then I'm generating the template and deploying it through

aws cloudformation deploy --template-file "$env:TEMP\template.json" --stack-name myStackName

Inside my Stack object, how can I retrieve the "myStackName" passed above to the command? I tried with .Name and .StackName properties but neither gave me that name.

Thanks

like image 933
Ariel Avatar asked Feb 03 '23 18:02

Ariel


2 Answers

This is done via pseudo parameters.

import * as cdk from "@aws-cdk/core";

// in your construct...
const stack = cdk.Stack.of(this);
stack.stackName
like image 123
alukach Avatar answered Feb 24 '23 13:02

alukach


The recommended approach is this described by alukack. But you can also do

Aws.STACK_NAME

But as described in the above link...

CloudFormation supports a number of pseudo parameters, which resolve to useful values at deployment time. CloudFormation pseudo parameters can be obtained from static members of the Aws class.

It is generally recommended to access pseudo parameters from the scope's stack instead, which guarantees the values produced are qualifying the designated stack, which is essential in cases where resources are shared cross-stack:

BTW: I experienced that the stack.stackName returned the id of the stack which I used in CDK.. The correct Stackname used in CFN was only returned from the Aws.STACK_NAME.

like image 22
H6. Avatar answered Feb 24 '23 13:02

H6.