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
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"
}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.
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-identityThis 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:
optionalpermits IMDSv1 and IMDSv2;requireddisallows tokenless IMDSv1 requests. - HttpEndpoint:
enabledmakes the metadata endpoint available;disabledprevents 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 enabledBefore 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
SecretAccessKeyorToken. - 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
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, andTokenmust be treated as one temporary credential set.Expirationmatters 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.