Skip to the workspace
Pebellslearn by building
EC2 — Virtual Servers  ›  Lesson

User Data Scripts

User Data Scripts 12 minUser data is a script passed to an EC2 instance at launch that runs once, as root, on its first boot, so a fresh server can set itself up without anyone logging in.

aws / User Data Scripts

Explore each scene at your own pace.

01 · The rule

The rule

User Data Scripts

Every time Inkwell launches a new web server, the developer logs in and types the same commands: install nginx, start it, copy the site. On book-launch days, when servers need to appear quickly, that manual routine is too slow and too easy to get wrong. EC2 can run the routine for you.

The rule

User data runs once, as root, at first boot.

User data is text you hand to an instance when you launch it. If it is a script, a tool on the image called cloud-init runs it during boot:

#!/bin/bash
dnf install -y nginx
systemctl enable --now nginx
echo "Inkwell Books is open" > /usr/share/nginx/html/index.html

Each part of the rule is a rule to design around:

  • Once: by default the script runs only on the first boot. Stopping and starting the instance does not run it again.
  • As root: the script already has full rights, so no sudo is needed. It also means a mistake can do real damage.
  • At first boot: it runs before anyone could log in, so it cannot ask questions. Every command must work unattended, which is why dnf install gets the -y flag.

Practical limits: user data is capped at 16 KB, so large setups should download their files from somewhere like S3 rather than embed them. The first line decides how it is read; #!/bin/bash marks a shell script. And user data is not secret: anyone who can view the instance's settings can read it, so passwords belong in a service such as AWS Secrets Manager instead.

If the site does not come up, read the script's output on the instance at /var/log/cloud-init-output.log.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.