Every EC2 instance has access to its own metadata — information about itself — available at a special IP address. User Data is a startup script that runs when the instance first boots.
# Available at: http://169.254.169.254/latest/meta-data/
# (Only accessible from within the EC2 instance)
# Common metadata endpoints:
curl http://169.254.169.254/latest/meta-data/instance-id
# i-1234567890abcdef0
curl http://169.254.169.254/latest/meta-data/local-ipv4
# 10.0.1.15
curl http://169.254.169.254/latest/meta-data/public-ipv4
# 54.123.45.67
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/
# Returns the IAM role name attached to this instance
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/MyRole
# Returns temporary access key, secret, session token
# IMDSv2 requires a token for security (protects against SSRF attacks)
# Get a token first:
TOKEN=$(curl -X PUT 'http://169.254.169.254/latest/api/token'
-H 'X-aws-ec2-metadata-token-ttl-seconds: 21600')
# Then use token in requests:
curl http://169.254.169.254/latest/meta-data/instance-id
-H "X-aws-ec2-metadata-token: $TOKEN"
#!/bin/bash
# This script runs ONCE on first boot
# Logs: /var/log/cloud-init-output.log
yum update -y
yum install -y nginx
echo 'Hello from EC2!
' > /usr/share/nginx/html/index.html
service nginx start
chkconfig nginx on
# Install application
git clone https://github.com/mycompany/myapp /opt/myapp
cd /opt/myapp && pip install -r requirements.txt
systemctl start myapp