How to specify parameter definition in CDK stack?

zdenko.s picture zdenko.s · Sep 27, 2019 · Viewed 8.6k times · Source

Use an AWS CloudFormation Parameter section of AWS CDK mentions how to customize your AWS CloudFormation templates. It refers to cloud formation template. I would like to add parameters to my CDK stack and get parameters section of synthesised CF template.

Do I understand correctly that documentation suggests to add parameters section to synthesised template? If yes, it will be overwritten with every run of cdk synth.

Any other way to define parameters section?

Answer

mschenke picture mschenke · Sep 29, 2019

Edit: Here is a typescript example that reads a bucket name from the context: https://github.com/cloudshiftstrategies/aws-cdk-examples/tree/master/context-example-typescript-app

You can add parameters to the CDK using the CfnParameter type like so:

new cdk.CfnParameter(this, 'MyParameter', {
    type: 'String',
    default: 'Blah',
    noEcho: true,
});

But that is generally discourages by the CDK. The design is to have fully deployable stacks and use code/config as the conditions for what should be created for a given account. This is from their documentation:

When you run the cdk synth command for an app with multiple stacks, the cloud assembly includes a separate template for each stack instance. Even if the two stacks are instances of the same class, the AWS CDK emits them as two individual templates.

You can synthesize each template by specifying the stack name in the cdk synth command. The following example synthesizes the template for stack1.

This approach is conceptually different from how AWS CloudFormation templates are normally used, where a template can be deployed multiple times and parameterized through AWS CloudFormation parameters. Although AWS CloudFormation parameters can be defined in the AWS CDK, they are generally discouraged because AWS CloudFormation parameters are resolved only during deployment. This means that you cannot determine their value in your code. For example, to conditionally include a resource in your app based on the value of a parameter, you must set up an AWS CloudFormation condition and tag the resource with this condition. Because the AWS CDK takes an approach where concrete templates are resolved at synthesis time, you can use an if statement to check the value to determine whether a resource should be defined or some behavior should be applied.

Parameters in the cdk would be done through context values either from the command line or via the cdk.json as documented here: https://docs.aws.amazon.com/cdk/latest/guide/get_context_var.html