📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials AWS Solutions Architect EC2 Instance Metadata and User Data

EC2 Instance Metadata and User Data

4 min read Quiz at the end
Use EC2 instance metadata for dynamic configuration and User Data scripts for automated bootstrapping. Understand IMDSv2 security requirements.

EC2 Instance Metadata and User Data

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.

Teacher Note: Instance metadata is like a name badge that every EC2 instance wears. The instance can read its own badge to find out: what region am I in? what is my IP address? what IAM role do I have? Applications running on the instance can query this badge without any special permissions.

Instance Metadata Service (IMDS)

# 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 — Secure Metadata Access

# 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"

User Data — Bootstrap Scripts

#!/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
Exam Tip: Always require IMDSv2 on all EC2 instances — it protects against Server-Side Request Forgery (SSRF) attacks where malicious code tries to read instance metadata to steal IAM credentials. Enforce IMDSv2 via AWS Config rule or in your Launch Templates.
Topic Quiz · 1 questions

Test your understanding before moving on

1. An Auto Scaling Group launches new EC2 instances but the application takes 3 minutes to initialise before it can serve traffic. Instances receive traffic before being ready. What is the BEST solution?
💡 Lifecycle Hooks pause the instance in a Pending:Wait state until your code signals completion — preventing traffic from reaching unready instances.