preview-environments-per-pull-request-using-aws-cdk-and-github-actions icon indicating copy to clipboard operation
preview-environments-per-pull-request-using-aws-cdk-and-github-actions copied to clipboard

How to use dynamic stack names?

Open zeekrey opened this issue 1 year ago • 3 comments

Hey there! 👋🏻 Great job! Your work really helped me kick off this topic.

Anyone familiar with handling dynamic stack names? Picture this: I aim to create stacks tied to merge requests (where a stack sticks around, gets changes, and vanishes when a MR is shut). How do I find the stack reference that needs to go when a merge request is closed?

zeekrey avatar Jun 02 '24 22:06 zeekrey

@zeekrey My pleasure!

Usually what you want is to derive the stack name from the current git branch name. You need to get the merged branch name, and then you can obtain your stack name.

Something like this:

    - name: Destroy
      env:
        STAGE: ${{ github.head_ref }}
      run: yarn workspace @snaplet/infrastructure destroy

Then in your CDK code:

new DynamicStack(
  app,
  // max length of a stack name is 128 characters
  `DynamicStack${pascalCase(process.env.STAGE)}`.substring(0, 128),
  {
    alb: stableStack.alb,
    cloudfront: stableStack.cloudfront,
    cloudMapNamespace: stableStack.cloudMapNamespace,
    env: {
      account: process.env.CDK_DEFAULT_ACCOUNT,
      region: process.env.CDK_DEFAULT_REGION,
    },
    hostedZone: stableStack.hostedZone,
    vpc: stableStack.vpc,
    worker: stableStack.worker,
  }
)

jgoux avatar Jun 03 '24 06:06 jgoux

Thanks @jgoux for the fast reply. 😊

I thought about this as well, but how to reference the stack name in the destroy command? In your CDK example, the stack would be called something like 'DynamicStackmain'. How am I supposed to use this stack name in the destroy CLI command? I would need to call the pascalCase function again to generate the stack name a second time. Or is there a way to programmatically destroy the stack instead of using the CLI command?

zeekrey avatar Jun 03 '24 11:06 zeekrey

Oh, I see.

Here is my destroy command: cdk destroy --force --exclusively "DynamicStack*"

You can use the wildcard character so you don't have to specify the whole stack name. 🪄

Here is the docs about the patterns usage: https://docs.aws.amazon.com/cdk/v2/guide/cli.html#cli-stacks

jgoux avatar Jun 03 '24 13:06 jgoux