Retrieve IAM Role Security Credentials from Amazon EC2 Instance Metadata
Learn how EC2 applications obtain temporary IAM role credentials through IMDSv2, use them with AWS SDKs and CLI, handle rotation, and secure metadata access.
Applications running on Amazon EC2 can authenticate to AWS services without storing long-lived access keys. When an IAM role is attached to an instance, the EC2 Instance Metadata Service (IMDS) makes temporary AWS security credentials available locally to software on that instance.
AWS security credentials are authentication material used to sign AWS API requests. Temporary role credentials normally contain an access key ID, a secret access key, and a session token. They also include an expiration time.
Why EC2 Workloads Use Temporary Role Credentials
An EC2 application can use the credentials supplied for its attached IAM role to call services such as Amazon S3, Amazon DynamoDB, or AWS STS. The application does not need an IAM user access key embedded in source code, an image, or a configuration file.
| Credential type | Typical lifetime | Main concern | Recommended use on EC2 |
|---|---|---|---|
| IAM user access keys | Long-lived until disabled or rotated | Can remain exposed if copied into code, images, or logs | Avoid for workloads when an IAM role is suitable |
| EC2 role credentials | Temporary and automatically rotated | Applications must refresh them before expiration | Preferred method for EC2 applications |
Role credentials provide four important benefits:
- No embedded secrets: applications can obtain credentials at runtime.
- Automatic rotation: temporary values are replaced before they expire.
- Scoped permissions: the role can allow only the actions and resources the workload needs.
- Auditable access: AWS activity can be associated with the assumed role and reviewed through services such as CloudTrail.
IAM Roles and Instance Profiles
An IAM role is an AWS identity that has two related policy concepts. Its permission policies specify what the role can do. Its trust policy specifies which principal may assume the role. For an EC2 role, the trust relationship permits the Amazon EC2 service to assume the role for the instance.
An instance profile is the EC2 resource used to associate an IAM role with an EC2 instance. In common configurations, an instance profile contains one IAM role. The instance profile is what EC2 attaches, while the role supplies the trust relationship and permissions.
Attaching a Role
- During launch, select an instance profile containing the intended role.
- For an existing instance, associate an instance profile with the instance.
- An administrator can replace the association when the workload needs a different role. Applications should not assume that a role change is instantaneous or that previously cached credentials change immediately.
The role provides credentials, but it does not automatically grant broad access. IAM policy evaluation still determines whether each requested AWS action is allowed.
Amazon EC2 Instance Metadata Service
The Instance Metadata Service (IMDS) is a link-local service reachable from an EC2 instance. The standard IPv4 metadata address is 169.254.169.254. It exposes instance information and, when an IAM role is attached, role credential information.
Metadata access is local to the instance. It is not an internet-facing AWS API request and normally does not require internet connectivity. Local processes, network namespaces, proxies, firewall rules, and container networking can nevertheless affect access.
The IAM role credential path is:
/latest/meta-data/iam/security-credentials/
A request to that path lists the role name. Appending the returned role name requests the temporary credential document.
IMDSv2 Credential Retrieval Flow
IMDSv2 is the token-oriented version of IMDS. A client first obtains a time-limited metadata token with an HTTP PUT request. It then includes that token in the X-aws-ec2-metadata-token header on metadata GET requests.
- Request a token and specify its lifetime with
X-aws-ec2-metadata-token-ttl-seconds. - Use the token to list the attached role name.
- Use the token and role name to retrieve the credential document.
- Use the credentials through an SDK or CLI credential provider.
The token expires after its time-to-live. Request a replacement token when it expires or when a new metadata session is needed. A token is not an AWS access key and cannot be used to sign normal AWS service requests.
Request a Metadata Token
TOKEN=$(curl -sS -X PUT "http://169.254.169.254/latest/api/token" \
-H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
List the Attached Role Name
curl -sS \
-H "X-aws-ec2-metadata-token: $TOKEN" \
"http://169.254.169.254/latest/meta-data/iam/security-credentials/"
The response is the role name, usually as plain text. Store it in a variable rather than guessing it.
Retrieve the Credential Document
ROLE_NAME=$(curl -sS \
-H "X-aws-ec2-metadata-token: $TOKEN" \
"http://169.254.169.254/latest/meta-data/iam/security-credentials/")
curl -sS \
-H "X-aws-ec2-metadata-token: $TOKEN" \
"http://169.254.169.254/latest/meta-data/iam/security-credentials/$ROLE_NAME"
Treat the response as secret material. Do not print it in application logs, commit it to source control, or save it as permanent configuration.
Credential Metadata Response Fields
| Field | Purpose | Handling guidance |
|---|---|---|
AccessKeyId | Identifies the temporary access key used to sign requests | Use with the secret access key and session token; do not treat it as permanent |
SecretAccessKey | Secret signing component for AWS requests | Keep confidential and never log or persist unnecessarily |
Token | Session token associated with the temporary credentials | Required along with the access key ID and secret access key |
Expiration | Time at which the credentials stop being valid | Refresh before this time; it proves the values are temporary |
Code | Credential response status, commonly indicating success | Check it when manually diagnosing metadata responses |
Type | Identifies the credential type returned by the service | Use it as response metadata, not as a replacement for the credential values |
The session Token is essential. Sending only AccessKeyId and SecretAccessKey causes requests made with temporary credentials to fail.
Using the AWS CLI and SDKs
Current AWS SDKs and the AWS CLI can retrieve EC2 role credentials automatically through their default credential provider chains. A credential provider chain is an ordered set of sources that an SDK or CLI checks for usable credentials.
Prefer this automatic resolution over parsing IMDS JSON in application code. SDK providers understand expiration and can refresh role credentials. The CLI can also use the instance role without manually exporting values:
aws sts get-caller-identity
A successful response identifies the AWS account and the current caller ARN. Use it to verify which role the CLI is actually using.
Credential Source Selection
| Credential source | Typical use case | Rotation behavior | Security considerations |
|---|---|---|---|
| EC2 instance role via IMDS | Applications running directly on EC2 | Temporary and refreshed by supported providers | Protect metadata access and use least privilege |
| Environment variables | Local development, automation, or explicit overrides | Usually does not rotate automatically | Can leak through process inspection, diagnostics, or deployment configuration |
| Shared AWS credentials file | Developer profiles and local CLI use | Depends on the configured credentials | Protect file permissions and avoid placing it in machine images |
| Explicit application configuration | Specialized integrations | Usually manual | Highest risk when secrets are hard-coded or cached |
| ECS task role | Applications running as Amazon ECS tasks | Temporary and task-scoped | Prefer task credentials over the underlying EC2 role |
| EKS workload identity | Applications running in Amazon EKS | Depends on the configured pod identity mechanism | Use workload-level identity instead of sharing node credentials |
Provider precedence varies by SDK and configuration, but environment variables, shared credential profiles, and explicit credentials can take precedence over IMDS. If a CLI or SDK uses an unexpected identity, inspect environment variables, selected profiles, shared credential files, and explicit configuration before diagnosing IMDS.
For broader credential concepts, see Temporary Credentials and AWS Credentials.
Rotation and Application Behavior
AWS rotates temporary role credentials automatically before they expire. Supported SDK default providers normally monitor expiration and obtain fresh values without application code handling secret strings.
Create SDK clients with the SDK's default, refresh-capable credential provider. Do not fetch a document once at startup and cache its access key, secret, and session token indefinitely. Long-running processes that do this eventually receive authentication failures after expiration.
- Expired credentials: refresh the provider and retry according to the SDK's normal retry behavior.
- Metadata blocked: the provider may be unable to obtain new values; restore permitted metadata access or use the intended workload identity mechanism.
- Role changed: new credentials may represent a different role after the association updates, while existing clients may retain old values until their provider refreshes.
- Never persist temporary values: avoid writing them to files, logs, environment templates, or application databases.
IMDSv1 and IMDSv2
| Characteristic | IMDSv1 | IMDSv2 |
|---|---|---|
| Token requirement | No token is required | A token is required when the instance is configured to require IMDSv2 |
| Request pattern | Direct metadata GET requests | Token PUT, followed by token-bearing metadata GET requests |
| SSRF resistance characteristics | An SSRF vulnerability may be able to issue direct metadata requests | The token exchange adds a session requirement and makes many SSRF techniques harder |
| Recommended deployment posture | Use only when legacy compatibility is necessary and risk is understood | Require it for new and supported workloads |
| Compatibility considerations | Works with older clients | Older clients that do not support token requests may fail when tokens are required |
IMDSv2 reduces risk from server-side request forgery (SSRF), an application vulnerability in which an attacker causes a server to make requests to an address chosen by the attacker. It is not a substitute for fixing SSRF, restricting outbound behavior, or limiting which processes can reach metadata.
Metadata Service Security Configuration
EC2 metadata options control how workloads reach IMDS:
- HTTP endpoint: enable or disable metadata access.
- HTTP tokens: allow optional tokens for compatibility or require tokens for IMDSv2-only access.
- PUT response hop limit: limit how many network hops an IMDSv2 token response may traverse.
- Instance metadata tags: control whether instance tags are available through metadata when this feature is relevant to the workload.
Require IMDSv2 for new and supported workloads:
aws ec2 modify-instance-metadata-options \
--instance-id i-0123456789abcdef0 \
--http-tokens required \
--http-endpoint enabled \
--http-put-response-hop-limit 1
A hop limit of 1 is often appropriate for applications running directly on the host. Containers, proxies, and other network designs may require more than one hop. Increase it only when the design requires it, because a larger value can make metadata reachable across additional network paths.
For a new instance, metadata options and the instance profile can be set at launch:
aws ec2 run-instances \
--image-id ami-0123456789abcdef0 \
--instance-type t3.micro \
--iam-instance-profile Name=ExampleInstanceProfile \
--metadata-options HttpTokens=required,HttpEndpoint=enabled,HttpPutResponseHopLimit=1
Limit metadata access from untrusted processes and workloads. Web applications should not proxy arbitrary requests to 169.254.169.254. Network controls, process isolation, host firewalls, proxy exclusions, and application SSRF defenses should work together.
Permissions and Least Privilege
IMDS delivers credentials; IAM policies determine what those credentials can do. A role with unrestricted permissions turns a stolen or misused credential into a serious incident, even if the credentials are temporary.
For example, a workload that reads objects from one bucket might receive this conceptual customer-managed policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject"],
"Resource": "arn:aws:s3:::example-bucket/*"
}
]
}
AWS managed policies can be convenient and maintained by AWS, while customer-managed policies provide control over the exact actions and resources. In either case, grant only the permissions required by the workload. Review role policies, CloudTrail activity, and role usage regularly. Consider permissions boundaries, service control policies, resource policies, and explicit denies when evaluating access.
Containers and Special Environments
A container running on EC2 may be able to reach the host's instance role credentials through IMDS unless a container-specific credential mechanism is configured. This can unintentionally give several workloads the same permissions.
- Amazon ECS: use an ECS task role and task credentials for container-level permissions. See Task Credentials.
- Amazon EKS: use an EKS workload identity mechanism, such as pod identity, rather than relying on the node's instance role for every pod.
- Direct EC2 applications: use the instance role through the SDK provider chain and protect local metadata access.
Container network namespaces, firewall rules, proxies, and the IMDSv2 hop limit can prevent a container from reaching metadata. Before changing the hop limit, confirm whether the workload should use ECS task credentials or EKS workload identity instead.
Troubleshooting
| Symptom | Likely cause | Verification | Resolution |
|---|---|---|---|
| No role name returned | No role or instance profile, association not updated, or wrong path | Inspect the EC2 role association and request the role-listing path first | Associate the intended instance profile and retry after the association updates |
| IMDSv1 request returns 401 Unauthorized | IMDSv2 is required, or a token is expired or invalid | Make a new token PUT request | Include the token header on every metadata GET |
| Token request fails | Endpoint disabled, local firewall or namespace restriction, or unsuitable network path | Check metadata options and test from the instance host | Enable the endpoint when appropriate and correct local network controls |
| SDK reports no credentials | No role, unreachable metadata, proxy interference, or provider-chain override | Run an IMDSv2 request locally; inspect proxy variables, profiles, and environment variables | Restore intended metadata access or remove the unintended credential override |
| AWS request is AccessDenied | Role lacks the action or resource permission, or another policy layer denies it | Run aws sts get-caller-identity and review applicable policies | Grant the smallest required permission and investigate explicit denies |
| Container cannot access metadata | Hop limit, network rules, or an incorrect credential model | Test from the container and identify the orchestrator | Use task or pod identity where appropriate; adjust networking only when justified |
Typical Failure: Cached Credentials
If an application works initially and later fails authentication, it may have cached temporary values beyond their Expiration. Replace manual caching with the SDK default provider chain or another refreshable provider. Do not solve this by converting the role credentials into long-lived IAM user keys.
Recommended Operational Checklist
- Attach an instance profile containing a role with a correct EC2 trust policy.
- Require IMDSv2 unless a documented compatibility requirement prevents it.
- Keep the metadata endpoint enabled only when the workload needs it.
- Choose a hop limit based on the actual network design, especially for containers.
- Use AWS SDK or CLI provider chains instead of parsing metadata in application code.
- Verify the active principal with
aws sts get-caller-identity. - Use least-privilege policies and review CloudTrail activity.
- Prevent untrusted applications and SSRF-vulnerable web endpoints from reaching metadata.
- Use ECS task roles or EKS workload identity for orchestrated workloads when applicable.
The key distinction is simple: IMDS supplies temporary authentication material for the attached role, while IAM policies define the actions that role may perform. Secure metadata settings, refresh-capable providers, and least-privilege permissions make that arrangement practical for long-running EC2 workloads.