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.htmlEach 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
sudois 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 installgets the-yflag.
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.
The shortcut
Test each script with the three unattended checks: Could it run with nobody watching? Is it safe running as root? Is there nothing secret in it?
Nobody watching?
Without
-y,dnf install nginxwould stop to ask "Is this ok?". The flag answers yes by itself.
The common trap: editing user data on a stopped server and expecting it to rerun. By default it will not. Launch a new instance instead, which is the healthier habit anyway, since servers built the same way every time are easier to replace.
Drills
Answer fast — trust the rule.
When does a user data script run by default?
Which user runs a user data script?
Inkwell's script works when typed by hand but hangs as user data. What is the likely cause?
Where should the shop's database password go?
Remember
- User data runs once, as root, at first boot.
- Three unattended checks: nobody watching, safe as root, nothing secret.
- Trap: editing user data later does not rerun it; logs are in
/var/log/cloud-init-output.log.
