Latest

Retrieve IAM Role Security Credentials from Amazon EC2 Instance Metadata

Learn how EC2 applications obtain temporary IAM role credentials through IMDS, use IMDSv2 securely, understand credential fields, configure metadata options, and troubleshoot access.

Overview

An Amazon EC2 instance can receive an IAM role through an instance profile. Software running on that instance can then obtain temporary AWS credentials from the EC2 Instance Metadata Service (IMDS).

These credentials let applications call AWS APIs according to the policies attached to the role. They are different from long-lived IAM user access keys: AWS issues and refreshes role credentials automatically, and each credential set has an expiration time.

How EC2 Role Credentials Work

An IAM role is an AWS identity with permission policies. An instance profile is the EC2 attachment mechanism that associates a role with an instance. The relationship is:

  • The instance profile associates an IAM role with the EC2 instance.
  • IMDS exposes the role name and current temporary credentials to eligible software on the instance.
  • The role's policies determine which AWS API actions are allowed.
  • AWS replaces credentials as they approach expiration.

Temporary security credentials consist of an AccessKeyId, a SecretAccessKey, and a Token. The token is required because the credentials represent a temporary session.

Long-lived IAM user access keys are managed by people or applications and require deliberate rotation. Instance role credentials are designed for workloads: they are time-limited, automatically refreshed, and should not be embedded in source code or configuration files.

EC2 Instance Metadata Service

The EC2 Instance Metadata Service (IMDS) is a link-local HTTP service available from within an EC2 instance. Its IPv4 address is 169.254.169.254. Metadata is organized into hierarchical paths, including information about the instance, networking, and IAM role credentials.

IMDS is local to the instance. It is not a general public AWS API and should not be treated as a remote credential service. Access depends on instance metadata settings, networking, workload isolation, and the metadata protocol version in use.

The role credential category is available at /latest/meta-data/iam/security-credentials/.

The IAM Security Credentials Metadata Paths

PathRequest purposeExpected resultPrerequisites

/latest/api/token — Request an IMDSv2 session token — A token in the response body — IMDS endpoint enabled and a client able to send HTTP PUT.

/latest/meta-data/iam/security-credentials/ — Discover the attached role profile name — The role name associated with the instance profile — An instance profile and role must be attached; the metadata endpoint must be enabled.

/latest/meta-data/iam/security-credentials/<role-name> — Retrieve the role's current credential document — JSON containing temporary credentials and status fields — The role name must match the name returned by the category request.

Requesting the category without a role name returns the IAM role profile name associated with the instance. Supplying that name in the role-specific path returns the current credential document. If no suitable instance profile and role are attached, this path cannot provide usable role credentials.

IMDSv2 Access Flow

IMDSv2 is the token-oriented version of IMDS. A client first requests a metadata token with an HTTP PUT request. It then includes that token in the X-aws-ec2-metadata-token header on subsequent metadata requests.

The token time-to-live is supplied in the X-aws-ec2-metadata-token-ttl-seconds header. The service accepts a value from 1 through 21,600 seconds. The example below requests the maximum supported lifetime.

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

Use the token to discover the role name:

curl -sS -H "X-aws-ec2-metadata-token: $TOKEN" 'http://169.254.169.254/latest/meta-data/iam/security-credentials/'

After replacing ROLE_NAME with the returned role name, request the credential document:

curl -sS -H "X-aws-ec2-metadata-token: $TOKEN" 'http://169.254.169.254/latest/meta-data/iam/security-credentials/ROLE_NAME'

Credential Response Structure

A successful role-specific request returns a JSON credential document. A typical document contains fields similar to these:

{
  "Code": "Success",
  "LastUpdated": "2026-08-25T12:00:00Z",
  "Type": "AWS-HMAC",
  "AccessKeyId": "temporary-access-key-id",
  "SecretAccessKey": "temporary-secret-access-key",
  "Token": "temporary-session-token",
  "Expiration": "2026-08-25T18:00:00Z"
}

FieldMeaningSensitiveHow it is used

Code — Status of the credential response, such as Success — No — Check it when diagnosing retrieval failures.

LastUpdated — Time at which this credential set was last updated — No — Helps identify when the current set was issued or refreshed.

Type — Credential type reported by IMDS — No — Describes the returned credential format.

AccessKeyId — Public identifier for the temporary credential set — Usually not secret by itself — Sent as the access key identifier when signing AWS requests.

SecretAccessKey — Confidential signing key — Yes — Used by the SDK or CLI to sign requests; never log or disclose it.

Token — Temporary session token — Yes — Must accompany the access key ID and secret access key.

Expiration — Time after which the credential set is invalid — No — Refresh before this time rather than assuming credentials remain unchanged.

AccessKeyId, SecretAccessKey, and Token form one temporary session credential set. The Expiration value identifies when that set ceases to be valid. A response with an error code or unexpected status should be investigated before treating the returned fields as usable credentials.

IMDSv1 and IMDSv2

IMDSv1 is the older tokenless model: a client sends a metadata request directly without first obtaining a token. IMDSv2 requires the token exchange described above.

CharacteristicIMDSv1IMDSv2

Token requirement — No token — A valid token is required for metadata requests.

Request sequence — Send the metadata request — Send an HTTP PUT to /latest/api/token, then include the token header in metadata requests.

Security posture — Tokenless access can be easier to reach through some SSRF paths — The token requirement provides an additional defense against some server-side request forgery (SSRF) scenarios.

Compatibility considerations — Works with older scripts and clients — Legacy scripts must be updated to obtain and send a token.

Recommended configuration — Do not rely on it when stronger controls are available — Require IMDSv2 where possible.

Permitting tokenless requests can increase exposure when an untrusted application has a server-side request forgery vulnerability. Configure production instances to require IMDSv2, then test software that accesses metadata. A required-token setting can expose old scripts that assume IMDSv1.

Using Credentials in Applications

Supported AWS SDKs and the AWS CLI can detect EC2 role credentials through their normal default credential provider chains. This approach handles credential lookup and refresh without application code manually parsing the metadata response.

For example, an application should rely on the SDK's default provider chain rather than placing role credentials in environment variables or a configuration file. A Python application can use the default session without supplying access keys:

import boto3

s3 = boto3.client("s3")
response = s3.list_buckets()

The exact SDK API varies by language, but the design is the same: create the client without hard-coded credentials and let the SDK locate and refresh the EC2 role credentials.

The AWS CLI can likewise use the attached instance role:

aws sts get-caller-identity

This command identifies the AWS caller used by the CLI. It is useful for confirming that the expected role is being selected, but it does not grant additional permissions.

Manually exporting metadata credentials to environment variables is generally unnecessary and creates leakage risks through process inspection, shell history, diagnostic output, logs, or inherited environments. If direct retrieval is unavoidable, keep credentials in memory, minimize their lifetime, refresh before expiration, and never persist or transmit them unnecessarily.

IAM Authorization Model

Metadata access supplies credentials; it does not itself grant permission to perform AWS actions. Authorization is determined by the IAM role and all applicable policy controls.

  • Instance profile: The EC2 attachment that connects the instance to a role.
  • IAM role: The identity represented by the temporary credentials.
  • Role policies: Identity-based policies that allow or deny actions and resources.
  • Additional controls: Permissions boundaries, service control policies, resource policies, session policies, and explicit denies can further restrict access.

Use least privilege: grant each workload only the actions and resources it requires. Prefer separate, narrowly scoped roles for unrelated applications rather than one broad role shared by every process on an instance.

Configure Instance Metadata Access

EC2 metadata options control how the service can be reached:

  • HttpTokens: optional permits IMDSv1 and IMDSv2; required disallows tokenless IMDSv1 requests.
  • HttpEndpoint: enabled makes the metadata endpoint available; disabled prevents metadata access, including role credential retrieval through IMDS.
  • HttpPutResponseHopLimit: Controls how many network hops an IMDSv2 token response may traverse. Containers, proxies, and other network namespaces may require a suitable value, but increasing it can broaden reachability.
  • IPv4 and IPv6 endpoints: Metadata access can be configured for the IPv4 endpoint and, where supported and enabled, the IPv6 endpoint. Review both when designing network controls.

Inspect the settings for an instance:

aws ec2 describe-instances --instance-ids i-EXAMPLE --query 'Reservations[].Instances[].MetadataOptions'

Require IMDSv2 while keeping the endpoint enabled:

aws ec2 modify-instance-metadata-options --instance-id i-EXAMPLE --http-tokens required --http-endpoint enabled

Before disabling the endpoint, verify that applications, agents, and the AWS CLI do not depend on it for role credentials or other instance metadata.

Security and Operational Guidance

  • Never log, commit, display, or transmit SecretAccessKey or Token.
  • Limit which processes and users can run untrusted code on an instance.
  • Restrict network paths to the metadata address when workload isolation requires it.
  • Use separate roles for separate workloads and keep every role narrowly scoped.
  • Monitor API activity performed with the role through AWS audit tooling such as CloudTrail.
  • Design for rotation: temporary credentials change, and applications must not assume an access key remains valid indefinitely.
  • Use SDK or CLI refresh behavior instead of copying credentials into long-lived files or environment variables.

Troubleshooting Role Credential Retrieval

SymptomLikely causeVerification stepResolution

No role name or an unexpected response from the category path — No instance profile, an incorrect role association, or a disabled endpoint — Inspect the instance profile association and MetadataOptions — Attach or correct the instance profile and enable the endpoint when appropriate.

HTTP 401 Unauthorized — IMDSv2 is required but the token is missing, expired, or malformed — Request a new token and check that the header is exactly X-aws-ec2-metadata-token — Repeat the token request and include the new token in the metadata request.

HTTP 404 or an invalid path response — Incorrect path, role name, URL encoding, or trailing-path formatting — First request the category path, then use the exact returned role name — Correct the URL and avoid inventing a role name.

Metadata works on the host but fails in a container — Hop limit too low, container networking or proxy restrictions, or workload isolation — Test the container's route to the link-local address and inspect the hop-limit setting — Adjust the network design only if the workload should have metadata access; otherwise keep it blocked.

Credentials work initially and later expire — The script cached temporary credentials and did not refresh them — Compare the current time with Expiration — Use an SDK or CLI provider that refreshes automatically, or implement secure refresh handling.

AWS API calls return AccessDenied even though credentials were retrieved — The role policy or another policy control denies the action — Run aws sts get-caller-identity and evaluate role, resource, organization, boundary, and explicit-deny policies — Fix authorization policy design; do not replace role credentials manually.

Exam-Relevant Notes

  • The instance profile attaches a role to EC2; the role policies determine permissions.
  • The metadata category path returns the role name; the role-specific path returns the credential JSON.
  • IMDSv2 requires a token obtained with HTTP PUT and supplied in the metadata request header.
  • AccessKeyId, SecretAccessKey, and Token must be treated as one temporary credential set.
  • Expiration matters because role credentials are automatically rotated and are not permanent.
  • Metadata retrieval failure and AWS authorization failure are separate problems: a successful metadata request does not imply permission to call every AWS API.
  • Requiring IMDSv2 is preferable to leaving tokenless IMDSv1 access enabled.