DEV Community

Cover image for AWS CDK Typescript: Adding Custom Initialisation to EC2 Instances
Matthew Evan Eichler
Matthew Evan Eichler

Posted on

AWS CDK Typescript: Adding Custom Initialisation to EC2 Instances

In my last post, I introduced an AWS CDK Typescript example repository which can build and destroy two EC2 instances if you are taking the Linux Foundation LFS258 Kubernetes Fundamentals self-paced course. You can work on the course and tear down the Stacks at the end of the day to avoid any extra Cloud Costs.

But doing this over and over again can be tedious setting up the Ubuntu packages everytime you start the next day over. This is where the User Data for AWS EC2 virtuals machines comes in. You can introduce a script that gets executed each time a new EC2 instance is created, sparing you some extra time.

aventinesolutions/lfx-study-aws-cdk-kubernetes Pull Request #3

In this case,

  1. We first want to prepare our Ubuntu boxes with some changes to system configuration and ensure a couple of modules are loaded.
  2. We also use apt to fully update all packages
  3. Then we set up the package signing keys in a GnuPG keyring.
  4. Next, we install the Docker, Kubernetes and Helm packages required before we can start building our cluster according to the course.

After the Cloud Formation Stack has completed, how do I know my initialisation script worked correctly? I found the output in /var/log/cloud-init-output.log ...

...
Preparing to unpack .../helm_3.16.3-1_amd64.deb ...
Unpacking helm (3.16.3-1) ...
Setting up helm (3.16.3-1) ...
Processing triggers for man-db (2.10.2-1) ...
... etc
Enter fullscreen mode Exit fullscreen mode

You can use this as a pattern when you need also need a few set-up customisations for the EC2 image you use. However, if you have many changes from your chosen base image, then it would probably scale-up better to create your own custom Amazon Machine Image [AMI] from an EC2 instance that you have thoroughly tested (refer to this post "Build Your Own Ubuntu AMI" from @matrey Mathieu Rey)

Run Commands When You Launch an EC2 Instance with User Data Input on AWS Docs

Top comments (0)