AWS Systems Architect Professional

EC2 User Data, Instance Metadata, and IMDSv2 – SAP-C02 Study Guide

Learn how EC2 user data, instance metadata, and IMDSv2 support bootstrapping, instance discovery, security, and SAP-C02 architecture decisions.

AWS Systems Architect ProfessionalAWS Systems Architect ProfessionalUpdated Sep 1, 2026
Study options
WatchComing later
ListenComing later
ReadAvailable
ReviewComing later

Study guide

Technical reference and lesson notes

Purpose of This Lesson

Amazon EC2 provides two closely related capabilities for configuring and discovering instances:

  • User data bootstraps an instance during its initial launch.
  • Instance metadata provides information about the running instance through a link-local HTTP endpoint.

Together, they can automate software installation and generate instance-specific configuration without hard-coding values such as the instance ID, Availability Zone, AMI ID, or instance type.

This lesson also demonstrates the difference between IMDSv1 and IMDSv2, including the token requirement enforced by IMDSv2.

Key Concepts

EC2 instance metadata

The EC2 Instance Metadata Service (IMDS) is available from inside an instance at:

http://169.254.169.254/latest/meta-data/

The address is link-local and is intended to be accessed from the instance itself. Metadata can expose values such as:

  • Instance ID
  • AMI ID
  • Instance type
  • Availability Zone
  • Region-related placement information
  • Network interface details
  • IAM role credentials, when an instance profile is attached

Metadata paths are hierarchical. For example, a request under placement/ can expose placement-related values, while a request for placement/availability-zone returns the instance’s Availability Zone.

Applications and bootstrap scripts can use metadata to avoid embedding environment-specific values in code or configuration files.

IMDSv1 versus IMDSv2

IMDSv1 uses a simple HTTP request to retrieve metadata. For example:

curl http://169.254.169.254/latest/meta-data/instance-id

IMDSv2 uses session-oriented token authentication:

  1. The client sends an HTTP PUT request to obtain a metadata token.
  2. The token is included in a subsequent metadata request using the X-aws-ec2-metadata-token header.
  3. The token is valid for a configurable session duration, subject to the service limits.

A representative shell pattern is:

token=$(curl -X PUT \
  -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" \
  http://169.254.169.254/latest/api/token)

curl -H "X-aws-ec2-metadata-token: $token" \
  http://169.254.169.254/latest/meta-data/instance-id

If an instance is configured for IMDSv2 only, a request that does not provide a valid token is rejected. The setting is controlled through the instance metadata options, including the metadata version requirement and whether the endpoint is enabled.

IMDSv2 is preferred because the token exchange makes certain classes of unintended metadata access more difficult, particularly in architectures involving SSRF risks. It does not replace application-layer security or network and host hardening.

EC2 user data

User data is startup input supplied when an EC2 instance is launched. On Linux, it commonly contains a shell script beginning with a shebang such as:

#!/bin/bash

A typical bootstrap script might:

  1. Apply operating system updates.
  2. Install a package such as Apache HTTP Server.
  3. Start the service.
  4. Enable the service to start after reboot.
  5. Generate a web page containing values retrieved from instance metadata.

Example structure:

#!/bin/bash

yum update -y
yum install -y httpd
systemctl enable --now httpd

instance_id=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
ami_id=$(curl -s http://169.254.169.254/latest/meta-data/ami-id)
instance_type=$(curl -s http://169.254.169.254/latest/meta-data/instance-type)

cat > /var/www/html/index.html <<EOF
Instance ID: $instance_id<br>
AMI ID: $ami_id<br>
Instance type: $instance_type<br>
EOF

For an IMDSv2-only instance, the script must first obtain a token and include it in each metadata request. Production scripts should also include error handling, logging, package-management safeguards, and appropriate timeouts.

User data execution behavior

For standard EC2 Linux bootstrapping, user data is normally processed during the first boot through cloud-init. It is not automatically rerun on every reboot. This distinction matters when diagnosing failed deployments or when changing a script after an instance has already launched.

User data can be viewed from the EC2 console. Editing the value does not cause the updated script to execute immediately. A changed script generally requires an explicit cloud-init rerun or a new instance, depending on the desired lifecycle and operating-system configuration.

User data is best suited to initial bootstrapping, not as a general-purpose long-term configuration-management mechanism.

User data and metadata together

A useful pattern is to use user data for generic bootstrap logic and metadata for instance-specific values. The same script can therefore run on many instances while producing configuration tailored to each one.

For example, a single bootstrap script can install a web server and create a page displaying the instance’s identity. In a larger design, the same principle can be used to register an instance with a service, select an Availability Zone-specific configuration, or create an application node identifier.

Exam-Relevant Takeaways

  • User data is supplied at launch and is commonly used for first-boot automation.
  • User data does not automatically rerun on every reboot.
  • Instance metadata is accessed from within the instance through the link-local IMDS endpoint.
  • IMDSv2 requires a session token. Metadata requests without a valid token fail when the instance is configured for IMDSv2 only.
  • Prefer IMDSv2 over IMDSv1 for new workloads.
  • A script that calls IMDS must be compatible with the instance’s metadata-options setting.
  • Metadata can provide instance-specific information without hard-coding identifiers.
  • Editing user data on a running instance does not execute the modified content.
  • User data is not a substitute for tools such as AWS Systems Manager, Ansible, or other configuration-management systems for ongoing changes.
  • If user data installs software or starts a service, the security group must allow the required client traffic. For a web server, that commonly includes inbound TCP port 80 or 443, as appropriate.

Architecture Decision Guide

RequirementRecommended approachImportant consideration
Install packages and configure a service at launchEC2 user data/cloud-initUsually runs during first boot; add logging and failure handling
Retrieve the current instance ID or Availability ZoneEC2 Instance Metadata ServiceUse IMDSv2-compatible requests
Protect metadata access from unauthenticated requestsConfigure IMDSv2 onlyApplications and scripts must obtain and send a token
Apply configuration repeatedly across an instance fleetAWS Systems Manager, image pipelines, or configuration managementDo not rely solely on one-time user data
Build immutable, repeatable server imagesEC2 Image Builder or a controlled AMI pipelineReduces boot-time work and startup variability
Pass sensitive credentials to an instanceIAM roles, AWS Secrets Manager, or Systems Manager Parameter StoreDo not place long-lived secrets in user data
Identify an instance in an applicationMetadata or a generated registration identityAvoid assuming an instance ID remains stable after replacement

Common Exam Traps

  • Confusing user data with metadata: User data is input supplied to the instance; metadata is information returned by the EC2 platform.
  • Assuming user data runs on every reboot: Standard first-boot processing does not imply repeated execution.
  • Using an IMDSv1 request against an IMDSv2-only instance: The request fails because it lacks the required token.
  • Treating IMDSv2 as an IAM permission check: IMDSv2 token authentication is separate from IAM authorization. IAM roles still control access to AWS APIs.
  • Assuming user data changes take effect immediately: Updating the stored value does not automatically rerun the bootstrap script.
  • Putting secrets in user data: User data can be exposed through instance-management paths and should not contain unprotected long-lived credentials.
  • Forgetting network access requirements: A successfully bootstrapped web server is not reachable unless its security group permits the relevant inbound traffic.
  • Assuming instance metadata is available from anywhere: The IMDS endpoint is designed for access from the instance, not as a general external API.
  • Ignoring application compatibility: Enforcing IMDSv2 can break older agents or libraries that only know how to make IMDSv1 requests.

Real-World Engineer Notes

  • Prefer an AMI pipeline for stable base software and use user data for environment-specific initialization. This shortens boot time and reduces dependence on package repositories during scaling events.
  • Send bootstrap output to a known log, such as cloud-init logs, and make scripts fail visibly. A successful EC2 status check does not prove that user data completed successfully.
  • Make scripts idempotent where possible. Although user data is commonly first-boot logic, operators may rerun portions of it during recovery or troubleshooting.
  • Use IMDSv2 and restrict metadata access where supported. Also review SSRF protections, application proxy behavior, and host-level controls.
  • If an instance profile is attached, metadata can expose temporary role credentials to processes that can reach the relevant credentials path. Prevent untrusted workloads from accessing the host or metadata service.
  • Do not use an instance ID as a permanent business identity. Auto Scaling replacement, restoration, or instance recreation produces a new instance ID.
  • For fleet-wide operational actions, use Systems Manager rather than manually editing user data on individual instances.
  • Test bootstrap scripts with the exact AMI, operating system, package manager, IAM role, and metadata-options configuration used in production.

Quick Reference Summary

  • User data: Launch-time bootstrap input, commonly a shell script on Linux.
  • Metadata endpoint: http://169.254.169.254/latest/meta-data/
  • IMDSv1: Direct metadata requests; no token.
  • IMDSv2: Obtain a token with PUT, then send it in X-aws-ec2-metadata-token.
  • Typical metadata values: Instance ID, AMI ID, instance type, and Availability Zone.
  • Execution warning: User data generally runs during first boot, not automatically on every reboot.
  • Security preference: Require IMDSv2 for new workloads and avoid storing secrets in user data.
  • Operational preference: Use AMI pipelines and Systems Manager for repeatable fleet management.

Flashcards

1. What is EC2 user data used for?

Answer: Launch-time or first-boot automation, such as installing packages, writing configuration files, and starting services.

2. What is the EC2 Instance Metadata Service?

Answer: An instance-local HTTP service that exposes information about the running EC2 instance and, when configured, temporary credentials for its IAM role.

3. What is the IMDS endpoint?

Answer: http://169.254.169.254/latest/meta-data/

4. How does IMDSv2 authenticate requests?

Answer: The client first obtains a session token with an HTTP PUT request, then supplies that token in the X-aws-ec2-metadata-token header.

5. What happens when IMDSv2 is required and a client sends an IMDSv1-style request?

Answer: The request is rejected because it does not include a valid metadata token.

6. Does user data automatically run after every reboot?

Answer: No. Standard Linux first-boot processing normally runs it once unless cloud-init or another mechanism is explicitly configured to run it again.

7. Can user data be edited while an instance is running?

Answer: The stored value can be viewed and, in supported workflows, changed after stopping the instance, but changing it does not by itself execute the script.

8. How can a generic bootstrap script discover the current instance ID?

Answer: Query the instance metadata path for instance-id, using an IMDSv2 token when required.

9. Why is IMDSv2 preferred over IMDSv1?

Answer: Its token-based request flow provides stronger protection against certain unintended metadata access and SSRF-related scenarios.

10. Where should application secrets be stored instead of plain user data?

Answer: Use IAM roles for AWS API access and services such as AWS Secrets Manager or Systems Manager Parameter Store for managed secret or parameter retrieval.

Practice Questions

Question 1

A company launches EC2 instances with metadata options configured to require IMDSv2. A legacy startup script uses a direct curl request to retrieve the instance ID, but the request returns an authorization error. What is the best correction?

A. Add an inbound security-group rule for TCP port 80.
B. Attach a larger IAM policy to the instance profile.
C. Obtain an IMDSv2 session token and include it in the metadata request header.
D. Replace the instance with one using a public IPv4 address.

Correct answer: C

Explanation: IMDSv2 requires a token obtained through the metadata token endpoint. IAM permissions and public addressing do not replace the token requirement.

Question 2

An architect needs to install and start Apache automatically when a Linux EC2 instance is launched. The script should run only during initial provisioning. Which option is most appropriate?

A. Store the script in EC2 user data.
B. Store the script in instance metadata.
C. Add the script to the security group.
D. Use an Elastic IP address to trigger the script.

Correct answer: A

Explanation: User data is designed for launch-time and first-boot initialization. Metadata is a read-oriented source of instance information, not a script-storage mechanism.

Question 3

An Auto Scaling group replaces failed instances regularly. An application currently uses each instance ID as a permanent customer-facing identifier. What should the architect recommend?

A. Use the AMI ID as the permanent identifier.
B. Use the Availability Zone as the permanent identifier.
C. Generate and persist an application-level identity in durable storage.
D. Disable instance replacement in the Auto Scaling group.

Correct answer: C

Explanation: Instance IDs change when instances are replaced. A durable application identity must be generated and stored independently of the EC2 instance lifecycle.

Question 4

A team edits the user data of an already running EC2 instance and expects the new commands to install a package immediately. The package is not installed. Why?

A. User data is available only to Windows instances.
B. User data is generally processed during first boot and does not automatically rerun after editing.
C. Metadata must be disabled before user data can run.
D. User data requires an Elastic Load Balancer.

Correct answer: B

Explanation: Changing the stored user data does not execute it. The team must explicitly rerun the appropriate initialization mechanism or provision a new instance.

Question 5

A company wants to bootstrap a fleet with a common web-server configuration while minimizing startup time and avoiding unprotected credentials in user data. Which design is strongest?

A. Put all software, credentials, and configuration in user data.
B. Build a hardened AMI, use user data only for environment-specific initialization, and retrieve secrets through managed services.
C. Allow IMDSv1 because it requires less scripting.
D. Hard-code the instance ID and Availability Zone into the AMI.

Correct answer: B

Explanation: A tested AMI provides a consistent base, user data handles instance- or environment-specific work, and managed secret services avoid embedding long-lived credentials in bootstrap content.