Building an EC2 Instance with CDKv2 and Cloud-Init

Building an EC2 Instance with CDKv2 and Cloud-Init
SHARE

Overview

EC2

Cloud-init is a powerful way of configuring an EC2 instance. CDK can create an EC2 instance and use cloud-init to pass dynamically created variables to this EC2 instance which can be used to configure the instance. When combined, these tools can be used to create fully configured and deployed dynamic EC2 instances.

This GitHub repo will deploy an EC2 instance using CDK. This EC2 instance will download and install Asterisk 18 on the EC2 instance. Additionally, it will create a pjsip.conf file and configure that using the Elastic IP address created by the CDK.

Once the Elastic IP is created, by the CDK, it is passed to the EC2 Instance using cloud-init:

init: ec2.CloudFormationInit.fromConfigSets({ configSets: { default: ['install', 'config'], }, configs: { install: new ec2.InitConfig([ ec2.InitFile.fromObject('/etc/config.json', { IP: ec2Eip.ref, }),

This file will be stored on the newly created instance based on resources created by the CDK. In this example, the Elastic IP address is passed to the JSON object. This information can also be queried with metadata, but is used in this example as information that can be dynamically created by the CDK and passed to the EC2 Instance.

Files can be loaded to the EC2 instance from multiple sources. In this example, we are loading a bash script from the local deployment of the CDK and executing it on the EC2 instance. This cloud-init configuration in the CDK will load the install.sh file from the ./src/asteriskConfig/ directory into the /etc/ directory of the Instance and then execute it.

ec2.InitFile.fromFileInline( '/etc/install.sh', './src/asteriskConfig/install.sh', ), ec2.InitCommand.shellCommand('chmod +x /etc/install.sh'), ec2.InitCommand.shellCommand('cd /tmp'), ec2.InitCommand.shellCommand('/etc/install.sh'), ]),

The example script will download and install an Asterisk PBX on to the EC2 instance. Additional files are included in the GitHub repo that are used to more fully configure the Asterisk server using jq and sed with the information passed to the Instance from the CDK:

IP=$( jq -r '.IP' /etc/config.json ) sed -i "s/IP_ADDRESS/$IP/g" /etc/asterisk/pjsip.conf

initOptions can also be used to ensure that the configuration of the EC2 instance succeeds.

initOptions: { timeout: Duration.minutes(15), },

If the timeout fails or the Instance returns a failure, the CDK will roll back to the previous state. When the cloud-init configuration of the Instance succeeds, it will pass this information back to the CDK. Until then, the CDK will remain in a Creating state and will not progress. This is useful when you want to ensure that the build and configuration of the EC2 instance succeeds before deploying additional resources with the CDK.

More details are provided in the GitHub repo.