EC2 User Data Example in AWS CDK - Complete Guide

avatar

Borislav Hadzhiev

Fri May 07 20213 min read

banner

Photo by Mark Basarab

Adding User Data to an EC2 Instance in AWS CDK #

User data allows us to add commands to the startup script of an EC2 instance.

In order to add user data to an EC2 instance, we have to load the script from the local file system and pass it to the addUserData method on the instance.

lib/cdk-starter-stack.ts
import {readFileSync} from 'fs'; // ๐Ÿ‘‡ load user data script const userDataScript = readFileSync('./lib/user-data.sh', 'utf8'); // ๐Ÿ‘‡ add user data to the EC2 instance ec2Instance.addUserData(userDataScript);

In this article we're going to look at a complete example of creating an EC2 instance and adding user data to it. Our user data script installs and starts an apache web server.

The code for this article is available on GitHub

Let's look at the code for the complete example:

lib/cdk-starter-stack.ts
import * as ec2 from '@aws-cdk/aws-ec2'; import * as cdk from '@aws-cdk/core'; import {readFileSync} from 'fs'; export class CdkStarterStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); // ๐Ÿ‘‡ import default VPC const vpc = ec2.Vpc.fromLookup(this, 'my-default-vpc', { isDefault: true, }); // ๐Ÿ‘‡ create a security group for the EC2 instance const webserverSG = new ec2.SecurityGroup(this, 'webserver-sg', { vpc, }); webserverSG.addIngressRule( ec2.Peer.anyIpv4(), ec2.Port.tcp(80), 'allow HTTP traffic from anywhere', ); // ๐Ÿ‘‡ create the EC2 instance const ec2Instance = new ec2.Instance(this, 'ec2-instance', { vpc, vpcSubnets: { subnetType: ec2.SubnetType.PUBLIC, }, securityGroup: webserverSG, instanceType: ec2.InstanceType.of( ec2.InstanceClass.T2, ec2.InstanceSize.MICRO, ), machineImage: new ec2.AmazonLinuxImage({ generation: ec2.AmazonLinuxGeneration.AMAZON_LINUX_2, }), }); // ๐Ÿ‘‡ load user data script const userDataScript = readFileSync('./lib/user-data.sh', 'utf8'); // ๐Ÿ‘‡ add user data to the EC2 instance ec2Instance.addUserData(userDataScript); } }

Let's go over the code snippet.

  1. we imported the default VPC, in which we'll launch the EC2 instance
  2. we created a security group with the following inbound rule:
TypeProtocolPortSource
HTTPTCP800.0.0.0/0

We have allowed inbound HTTP traffic on port 80 from anywhere. Note that by default all outbound traffic is allowed.

  1. we created a t2.micro EC2 instance with AMAZON LINUX 2 AMI. The instance is launched in a public subnet of our VPC, because we'll use it as a web server.

  2. we loaded the user data script from the file system and passed it in a call to the addUserData method on the instance.

The code for this article is available on GitHub

Let's add the user data script, which installs and starts an apache web server, at lib/user-data.sh:

lib/user-data.sh
#!/bin/bash sudo su yum update -y yum install -y httpd systemctl start httpd systemctl enable httpd echo "<h1>Hello World from $(hostname -f)</h1>" > /var/www/html/index.html

The script installs and starts the apache webserver.

If our user data script works as intended, our web server should respond with a simple "Hello World" message, when we paste the instance's public IPv4 address in our web browser.

Next, we'll deploy and test our user data script.

Deploying our EC2 instance with User Data in AWS CDK #

Let's deploy the instance and test our user data script.

shell
npx cdk deploy

After about 5 minutes the EC2 instance is created.

Copy the Public IPv4 address of the instance:

ec2 instance public ipv4

And paste it in your browser:

ec2 instance response

We can see that the user data script we added to our EC2 instance, has installed and booted our apache web server successfully.

Clean up #

To delete the resources we provisioned, execute the destroy command:

shell
npx cdk destroy

Further Reading #

Add me on LinkedIn

I'm a Web Developer with TypeScript, React.js, Node.js and AWS experience.

Let's connect on LinkedIn

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee