Just Learn Code

Automating EC2 Instances with User Data in AWS CDK

Creating virtual machines can be an extremely tedious process. From configuring the virtual network, ensuring the correct ports are open, installing software, and configuring services, the process can take hours if not days.

Moreover, all these manual tasks need to be repeated for every virtual machine. This is where User Data comes in.

User Data is a script that is executed when an EC2 instance boots up. User Data can be used to install updates, software, and configure services, automating the entire process.

In this article, we will learn how to add User Data to an EC2 Instance in AWS CDK and write a

User Data Script that installs and starts up an Apache web server and then displays a message on a website.

Adding User Data to an EC2 Instance in AWS CDK

Amazon Web Services (AWS) Cloud Development Kit (CDK) is a software development framework for defining cloud infrastructure in code. User Data can be added to an EC2 instance in AWS CDK by using the addUserData method in the Instance Class.

User Data can be in the form of a script that is executed during the instance’s startup process. To add User Data to an EC2 instance, create a new Stack instance that will contain the instance and its supporting resources.

Then create a new VPC and a public subnet that will contain the instance. Add a security group and an inbound rule to allow traffic to the instance.

Finally, define the AMI (Amazon Machine Image) of the instance and call the addUserData method to add the script.

Complete example of creating an EC2 instance with User Data in AWS CDK

Below is an example of an AWS CDK script that creates an EC2 instance with User Data, installs an Apache web server, and displays a message on a website. “`

import * as cdk from ‘aws-cdk-lib’;

import * as ec2 from ‘aws-cdk-lib/aws-ec2’;

import * as iam from ‘aws-cdk-lib/aws-iam’;

import * as ssm from ‘aws-cdk-lib/aws-ssm’;

const app = new cdk.App();

const stack = new cdk.Stack(app, ‘MyCDKStack’);

const vpc = new ec2.Vpc(stack, ‘MyVPC’, {

maxAzs: 2

});

const securityGroup = new ec2.SecurityGroup(stack, ‘MySecurityGroup’, {

vpc,

allowAllOutbound: true

});

securityGroup.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(80), ‘Allow HTTP traffic’);

const userData = ec2.UserData.forLinux();

userData.addCommands(‘yum update -y’, ‘yum install -y httpd’, ‘systemctl start httpd’, ‘systemctl enable httpd’);

userData.addCommands(‘echo “Hello World!” > /var/www/html/index.html’);

const instance = new ec2.Instance(stack, ‘MyInstance’, {

vpc,

instanceType: ec2.InstanceType.of(ec2.InstanceClass.T2, ec2.InstanceSize.MICRO),

machineImage: new ec2.AmazonLinuxImage(),

securityGroup,

userData

});

const instanceId = instance.instanceId;

new ssm.StringParameter(stack, ‘MyInstanceParameter’, {

parameterName: ‘/MyCDKStack/MyInstance/InstanceId’,

stringValue: instanceId

});

app.synth();

“`

The script creates a new VPC with a public subnet.

The security group allows inbound traffic on port 80 for HTTP traffic. The addUserData method is called to add the

User Data Script that installs and starts an Apache web server and displays “Hello World!” on a web page.

User Data Script

A User Data script is a script that is executed when an EC2 instance is launched. User Data can be used to install updates, software, and configure services.

A popular use case for User Data is to launch web servers such as Apache, Nginx or IIS. Content and Purpose of

User Data Script

Below is an example of a

User Data Script that installs and starts an Apache web server and displays “Hello World!” on a web page.

“`

#!/bin/bash

yum update -y

yum install -y httpd

systemctl start httpd

systemctl enable httpd

echo “Hello World!” > /var/www/html/index.html

“`

The User Data script installs an Apache web server using the package manager yum and starts the service using systemctl. The index.html file is created in /var/www/html, displaying the message “Hello World!”.

Testing

User Data Script

To test the

User Data Script, launch an EC2 instance using the script. Wait for the instance to launch and then note the Public IPv4 address of the instance.

Open a web browser and navigate to the Public IPv4 address. The web page should display the message “Hello World!”.

Conclusion

Adding User Data to an EC2 instance in AWS CDK is a powerful tool for automating the installation and configuration of software and services. User Data can save countless hours of manual work and provide consistent and reliable results.

The

User Data Script we provided in this article installs and starts an Apache web server, and displays a message on a website. Use this script to quickly set up an Apache web server and test the User Data feature in AWS CDK.

Clean Up

When working with AWS, it is important to ensure that resources are removed or destroyed, once they are no longer needed. This is particularly true when working in development or testing environments when resources are created and deleted frequently.

AWS provides tools to help make this process easier, such as the AWS Command Line Interface (CLI) and the AWS Cloud Development Kit (CDK). In this section, we will discuss how to clean up provisioned resources using the destroy command.

Deleting Provisioned Resources

Deleting EC2 instances, S3 buckets, Route 53 domains, or any other AWS resource is a relatively straightforward process. There are a few different ways to accomplish this, including using the AWS Management Console, the CLI, or SDKs. In this article, we will focus on deletion using the CLI.

To delete a provisioned resource using the CLI, you’ll need to identify the resource identifier. AWS resources are identified via their Amazon Resource Name (ARN), which is a unique identifier used across all AWS services.

To identify the resource ARN, you can use the describe command. The describe command is commonly available across AWS CLI commands and enables the user to retrieve information on an AWS resource.

For example, if you want to identify details about your EC2 instances, you can use the describe-instances command, which provides details about all running instances:

“`

aws ec2 describe-instances

“`

This command will return a wide range of details, including the instance ID, the instance type, its current state, the VPC it is running in, and more. Once you have identified the instance or other resource that you want to delete, you can use the delete command to remove it:

“`

aws ec2 terminate-instances –instance-ids i-1234567890abcdef0

“`

This command will destroy the specified instance. It is important to note that some resources may take time to delete, especially if they are large or there are dependencies on other resources.

Additional Resources

If you are interested in further learning about AWS CDK and using User Data, several resources can help. AWS provides several tutorials and documentation on these topics, including:

– AWS CDK Developer Guide: https://docs.aws.amazon.com/cdk/latest/guide/home.html

– AWS CDK Workshop: https://cdkworkshop.com/

User Data Script: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html

Additionally, there are many free and paid courses available through AWS and other providers, including:

– AWS Training and Certification: https://aws.amazon.com/training/

– Pluralsight: https://www.pluralsight.com/

– A Cloud Guru: https://acloudguru.com/

By taking advantage of these resources, you can develop your skills and knowledge in AWS and build advanced applications faster and with greater ease.

Conclusion

Cleaning up after provisioned resources is an essential aspect of developing and managing infrastructure. Using the AWS CLI or other tools can help simplify the process and prevent clutter.

AWS CDK and User Data scripts provide a powerful way to automate the creation and management of resources, saving development teams time and effort. By continuing to learn about AWS, you can strengthen your skills and leverage the full power of the cloud platform, ensuring that your applications are performant, secure, and scalable.

In this article, we learned about User Data and how to add it to an EC2 instance in AWS CDK. User Data can be used to automate the installation and configuration of services, such as Apache web server.

We also learned about cleaning up provisioned resources using the destroy command in the AWS CLI. Finally, we discussed how to find additional resources to continue learning about AWS.

The ability to automate resource management and clean up ensures that developer environments remain easy to use and free of clutter. As you continue to develop and work with AWS, remember to take advantage of the tools and resources available to simplify workflows and streamline your application development.

Popular Posts