Sub topic 10
Bootstrapping with user data
This chapter assumes you can launch an instance with the AWS CLI, as covered in the launch chapter. It also assumes you know basic Linux shell scripting and how security groups and IAM instance profiles attach to an instance.
What user data is
User data is a block of text you pass to an instance at launch. On Amazon Linux 2023 and most other AMIs, a program called cloud-init reads that text during first boot. If the text starts with a shebang line such as #!/bin/bash, cloud-init runs it as a script with root privileges.
This lets you start from a generic AMI and finish configuring it automatically. You can install packages, write config files, pull code, and start services without logging in over SSH.
User data is the simplest form of bootstrapping. The other common approach is to bake everything into a custom AMI. Bootstrapping is flexible and keeps images generic, but each launch repeats the work and takes longer to become ready.
A first example
This script installs and starts nginx on Amazon Linux 2023:
#!/bin/bash
dnf install -y nginx
systemctl enable --now nginxSave it as userdata.sh. Pass it with the --user-data option of run-instances. The AWS CLI accepts file:// for a file and encodes it for you:
AMI_ID=$(aws ssm get-parameter \
--name /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 \
--query Parameter.Value --output text)
aws ec2 run-instances \
--image-id "$AMI_ID" \
--instance-type t3.micro \
--key-name my-key \
--security-group-ids sg-0123456789abcdef0 \
--subnet-id subnet-0123456789abcdef0 \
--metadata-options HttpTokens=required \
--user-data file://userdata.sh \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=tutorial-web}]'The instance reaches the running state before the script finishes. Running does not mean configured. Wait for the script to complete before you test it.
For the web page to be reachable, the security group must also allow inbound TCP on port 80. The first security group in this tutorial only opens SSH, so add a rule for HTTP if you want to browse to the server.
How cloud-init processes user data
By default, cloud-init runs user data scripts only on the first boot of an instance. A reboot, or a stop followed by a start, does not run the script again. This is deliberate. A script that installs software and creates users should not repeat on every restart.
Cloud-init gets the data from the instance metadata service. If you require IMDSv2 with HttpTokens=required, cloud-init still works, because current cloud-init versions on AWS images support session tokens.
Limits and encoding
- User data is limited to 16 KB before base64 encoding. If your script is larger, have it download the real script from Amazon S3 and run that.
- The AWS CLI base64-encodes the value for you. If you call the API directly or use a tool that does not encode, you must encode it yourself.
- You can change user data only while an instance is stopped. A change does not make it run again unless you also configure cloud-init to do so.
Format options
Besides shell scripts, cloud-init accepts a declarative format called cloud-config. It must begin with the line #cloud-config:
#cloud-config
packages:
- nginx
runcmd:
- systemctl enable --now nginxCloud-config is easier to read for package installs and file writes. A shell script gives you full control with conditionals and loops. Choose the script when you need logic, and cloud-config when you only need to declare a desired state.
Debugging a bootstrap that did not work
A failed script does not stop the instance from launching, so a typo can leave you with a running but misconfigured server. Connect over SSH and check the logs:
| File | What it contains |
|---|---|
| `/var/log/cloud-init-output.log` | Output and errors from your script |
| `/var/log/cloud-init.log` | Cloud-init's own detailed activity |
You can also ask cloud-init for an overall result:
cloud-init status --longA status of done means cloud-init finished, not that your script succeeded. Read the output log to see whether commands failed. To make failures visible, start your script with set -euo pipefail so it stops at the first error. Note that this also makes it stop on an unset variable, so use it deliberately.
Security considerations
User data is not private. Anyone who can reach the metadata service from the instance can read it, and anyone with the ec2:DescribeInstanceAttribute permission can read it through the API. Do not put passwords, API keys, or private keys in user data.
Instead, give the instance an IAM role and have the script fetch secrets at boot from a service such as AWS Secrets Manager or Systems Manager Parameter Store. The role supplies temporary credentials, so nothing sensitive is stored in the launch request.
Also remember that the script runs as root. Pulling and running code from an untrusted location in user data gives that code full control of the instance.
Common errors
- Missing shebang. Without
#!/bin/bashon the first line, cloud-init does not treat the text as a script. - Package manager mismatch. The script above uses
dnf, which fits Amazon Linux 2023. Ubuntu usesapt-get, and older Amazon Linux 2 usesyum. - No outbound access. Installing packages needs a route to a package source. An instance in a private subnet needs a NAT gateway or VPC endpoints, or the install will fail.
- Assuming the script reran. Editing user data on a stopped instance does not rerun it by default.
- Interactive commands. Add
-yto installers. A prompt waits for input that never arrives. - Windows. Windows AMIs use a different mechanism, with scripts wrapped in
<powershell>tags, which is outside this chapter.
Exercise
You launch an instance with a user data script that installs nginx. The instance shows running, but a request to its public IP fails. List two things you would check, and say where you would find the script's errors.
Show answer
First, check the security group: it needs an inbound rule for TCP port 80, since security groups deny inbound traffic by default. Second, check whether the script finished and succeeded, because running only means the instance booted. Possible causes include a failed install from a missing shebang, a wrong package manager, or no outbound route. Connect over SSH and read /var/log/cloud-init-output.log for the script's output and errors.
Exercise
A teammate stores a database password in the user data script so the server can connect at boot. Why is this a problem, and what is a better design?
Show answer
User data can be read through the instance metadata service and through the EC2 API, so the password is exposed to anyone with access to either. A better design attaches an IAM role through an instance profile and has the script retrieve the password at boot from Secrets Manager or Parameter Store using the role's temporary credentials.