Learn about Amazon EC2 User Data » –

User Data is a very cool technique that you may overlook when using EC2 Service. User Data helps you to automatically install some packages before booting your EC2 server, a process called bootstrapping.

The actual bootstrapping process is asking the Amazon EC2 instance to run some commands (command) while booting as root (sudo su).

Script defined in User Data will be run only once on first boot (make sure not to run over and over again). In the AWS exam this is also a very frequently asked question about User Data running once or every time it starts.

Note: The script in User Data only runs once at first start.

Some of the jobs that User Data can help us do are as follows:

  1. Installing updates
  2. Installing software
  3. Downloading common files from the Internet

By default, commands in User Data will be run with the highest privilege as root.

User Data example:

#!/bin/bash
# install httpd
yum update -y
yum install -y httpd.x86_64
systemctl start httpd.service
systemctl enable httpd.service
echo "<h1>Hello AWS from $(hostname -f)</h1>" > /var/www/html/index.html

EC2 User Data is an important technique encountered a lot in the AWS exam as well as in working practices related to virtualized workloads on AWS. Hopefully through this article you can understand User Data and how to use it.

Adding a little bit of difficulty, we can also use User Data script to get EC2 Metadata related parameters.

Code: $(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone/)

Combining the above with User Data, we get a complete script as follows:

#!/bin/bash
# install httpd
yum update -y
yum install -y httpd.x86_64
systemctl start httpd.service
systemctl enable httpd.service
EC2_AZ=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone/)
echo "<h1>Hello AWS from $(hostname -f) in AZ: $EC2_AZ</h1>" > /var/www/html/index.html

Happy Clouding!

Leave a Reply