User Data (Bootstrapping)

User data is a startup script that runs the first time an instance boots, so it can configure itself automatically.

User data is a script you pass at launch. On first boot the instance runs it as root, which lets you install packages, download code and start services without logging in.

How it works

  • Provide a shell script (starting with #!/bin/bash) or a cloud-init config.
  • It runs once at the initial boot by default.
  • Combined with an AMI, it turns a blank server into a working one automatically.

Why it matters

User data is the foundation of immutable infrastructure and Auto Scaling: every new instance bootstraps itself the same way, so servers are disposable and repeatable.

Example

Example · bash
# A user-data script that installs and starts a web server
cat > startup.sh <<'EOF'
#!/bin/bash
dnf update -y
dnf install -y httpd
systemctl enable --now httpd
echo "<h1>Hello from $(hostname -f)</h1>" > /var/www/html/index.html
EOF

aws ec2 run-instances \
  --image-id ami-0abcd1234efgh5678 \
  --instance-type t3.micro \
  --user-data file://startup.sh

When to use it

  • A launch template includes a user data script that installs nginx and starts the service so every new Auto Scaling instance is immediately ready.
  • A user data script fetches application secrets from AWS Secrets Manager at boot time rather than hard-coding them into the AMI.
  • A data pipeline EC2 instance uses user data to mount an EFS share and start a processing job automatically on first boot.

More examples

Launch Instance with Startup Script

Passes a bootstrap script as user data that installs and starts Apache on first boot, making the instance self-configuring.

Example · bash
aws ec2 run-instances \
  --image-id ami-0abcdef1234567890 \
  --instance-type t3.micro \
  --user-data '#!/bin/bash
yum update -y
yum install -y httpd
systemctl enable httpd
systemctl start httpd
echo "Hello from EC2" > /var/www/html/index.html'

User Data from a File

Reads the startup script from a local file, keeping the launch command clean and the script in version control.

Example · bash
# bootstrap.sh
#!/bin/bash
apt-get update -y
apt-get install -y docker.io
systemctl enable docker
systemctl start docker
docker run -d -p 80:80 nginx

# Launch using the file
aws ec2 run-instances \
  --image-id ami-0abcdef1234567890 \
  --instance-type t3.small \
  --user-data file://bootstrap.sh

Retrieve User Data on Running Instance

Fetches the user data script from the instance metadata service, useful for debugging what ran at boot.

Example · bash
# Run from inside the EC2 instance
TOKEN=$(curl -s -X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" \
  http://169.254.169.254/latest/api/token)

curl -s -H "X-aws-ec2-metadata-token: $TOKEN" \
  http://169.254.169.254/latest/user-data

Discussion

  • Be the first to comment on this lesson.