Specifying User Data for EC2

Learn about EC2 user data and what it can be used for.

In this lesson, we will learn about a very useful feature called EC2 user data. Looking at the name, it isn’t immediately obvious what it does, so let’s look into it: “When you launch an instance in Amazon EC2, you have the option of passing user data to the instance that can be used to perform common automated configuration tasks and even run scripts after the instance starts.” 7^7

This means that EC2 user data is a script that runs on the first boot of an instance. It’s important to remember that it only runs once. If we start and stop the instance, it will not run again.

AWS supports two formats for this script—a standard shell script and a cloud-init file. a cloud-init file is a configuration file specifically used for cloud providers. AWS uses them to set up our SSH keys within the instance. In this lesson, we’ll learn to use shell scripts with EC2 user data.

This script will be executed as the root user, so it has full access to the system.

But what would we use this for?

We can use the EC2 user data script for almost anything, like:

  • Installing a software
  • Updating a software
  • Starting services
  • Changing configuration
  • Running tests

However, as a general rule, we should only run things in the EC2 user data script that we cannot add to the underlying AMI directly. For example, it’s better to install software directly into the AMI so the instance does not need to spend time on downloading and installing it and therefore will start faster. But, if we need to give every EC2 instance a special configuration (like an ID), this is something we could do in the EC2 user data.

Here’s a rule of thumb to decide what goes into the AMI and what goes into the EC2 user data: If it is static and does not differ between similar EC2 instances, put it in the AMI. If it is dynamic, like individual configuration, we should use EC2 User Data to set it up.

Hello world! user data

Let’s try a small example of how we could use EC2 user data to configure an Amazon Linux AMI as a web server.

The steps required to do this are:

  1. Create an EC2 instance based on an Amazon Linux AMI.
  2. Install the web server.
  3. Start (enable) the web server.
  4. Configure it so that it shows Hello world!.

Creating an EC2 instance is straightforward; we’ve done it before. So, the base command we use should be something like this:

Get hands-on with 1200+ tech skills courses.