CDK and Parameters
Create Template that accepts Parameters
CloudFormation templates are easy to share with any account. Parameters can be included in the CloudFormation template allowing the user to customize the infrastructure while retaining the authors original design intent. After uploading the template to a S3 bucket, anyone with permissions to the S3 bucket can use the template from the cli or console.
Instructions
Last example we created a VPC with one NAT Gateway. We can build on the previous example and add an EC2 instance where an end user can select the instance type from a dropdown menu before provisioning the infrastructure.
Add an EC2 instance
Let’s work in smaller chunks. Before adding the code for a parameter selecting the instance type, let’s get an instance provisioning correctly.
Open the file lib/create-vpc.ts from the previous exercise. Read the
AWS CDK Documentation documentation for creating an EC2 instance. We will use this
to create an instance. The EC2 instance will consume the parameter.
new ec2.CfnInstance(this, 'VpcInstance', {
imageId: 'ami-40d1f038',
subnetId: 'vpcid',
instanceType: 't3.large'
});
Add code to create an EC2 instances and deploy it. When the code is working proceed to the next section.
Add A parameter for the instance type
Open the AWS CloudFormation Template Reference and find the section on Parameters. The CloudFormation template reference is useful when using the CDK. Remember, the CDK transpiles to CloudFormation templates.
Parameters:
InstanceTypeParameter:
Type: String
Default: t2.micro
AllowedValues:
- t2.micro
- m1.small
- m1.large
Description: Enter t2.micro, m1.small, or m1.large. Default is t2.micro.
Our goal is to replicate this parameter section using AWS CDK.
Search the AWS CDK Documentation for Parameters.
const pInstanceType = new cdk.CfnParameter(this, 'instanceTypeParam', {
type: 'String',
default: 't3.small',
allowedValues: ['t3.small','t2.small', 't2.large']
});
const vpc = new ec2.VpcNetwork(this, 'VpcProps', {
natGateways: 1
});
new ec2.CfnInstance(this, 'VpcInstance', {
imageId: 'ami-40d1f038',
subnetId: vpc.publicSubnets[0].subnetId,
instanceType: pInstanceType.ref
});
Add the parameter section before the code for the EC2 instance.
To test the template, run the command cdk synth --output <file name>. Open the CloudFormation template.
Open the console navigate to the CloudFormation section. Create a new stack with the CloudFormation template.