Adding feature flags to AWS CDK through runtime context with projen

Adding feature flags to AWS CDK through runtime context with projen
SHARE

Feature flags are a way to modify the deployment behavior of an AWS SDK deployment. These are potentially breaking, so use with caution. These feature flags are stored in the context of the CDK as key-value pairs.

For example:

"context": { "@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true },

Here we are setting a feature flag to tell the CDK to always use a unique launch template name. This is useful when requiring imdsv2 for an EC2 instance.

const ec2Instance = new Instance(this, 'Instance', { vpc: props.vpc, instanceType: InstanceType.of(InstanceClass.C7G, InstanceSize.MEDIUM), machineImage: ubuntuAmi, requireImdsv2: true, userData: userData, ... })

Without this feature flag enabled, you are likely to get an error similar to this:

Launch template name already in use. (Service: AmazonEC2; Status Code: 400; Error Code: InvalidLaunchTemplateName.AlreadyExistsException;

To add this feature flag to the cdk.json file when using projen we must modify the .projenrc.ts file.

project.cdkConfig.json.addOverride('context', { '@aws-cdk/aws-ec2:uniqueImdsv2TemplateName': true, });

This will add the necessary context to the cdk.json file and enable the uniqueImdsv2TemplateName feature flag.

For a complete list of available feature flags available: https://github.com/aws/aws-cdk/blob/main/packages/%40aws-cdk/cx-api/FEATURE_FLAGS.md