Aws

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 typeTypical lifetimeMain concernRecommended use on EC2
IAM user access keysLong-lived until disabled or rotatedCan remain exposed if copied into code, images, or logsAvoid for workloads when an IAM role is suitable
EC2 role credentialsTemporary and automatically rotatedApplications must refresh them before expirationPreferred 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.

  1. Request a token and specify its lifetime with X-aws-ec2-metadata-token-ttl-seconds.
  2. Use the token to list the attached role name.
  3. Use the token and role name to retrieve the credential document.
  4. 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

FieldPurposeHandling guidance
AccessKeyIdIdentifies the temporary access key used to sign requestsUse with the secret access key and session token; do not treat it as permanent
SecretAccessKeySecret signing component for AWS requestsKeep confidential and never log or persist unnecessarily
TokenSession token associated with the temporary credentialsRequired along with the access key ID and secret access key
ExpirationTime at which the credentials stop being validRefresh before this time; it proves the values are temporary
CodeCredential response status, commonly indicating successCheck it when manually diagnosing metadata responses
TypeIdentifies the credential type returned by the serviceUse 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 sourceTypical use caseRotation behaviorSecurity considerations
EC2 instance role via IMDSApplications running directly on EC2Temporary and refreshed by supported providersProtect metadata access and use least privilege
Environment variablesLocal development, automation, or explicit overridesUsually does not rotate automaticallyCan leak through process inspection, diagnostics, or deployment configuration
Shared AWS credentials fileDeveloper profiles and local CLI useDepends on the configured credentialsProtect file permissions and avoid placing it in machine images
Explicit application configurationSpecialized integrationsUsually manualHighest risk when secrets are hard-coded or cached
ECS task roleApplications running as Amazon ECS tasksTemporary and task-scopedPrefer task credentials over the underlying EC2 role
EKS workload identityApplications running in Amazon EKSDepends on the configured pod identity mechanismUse 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

CharacteristicIMDSv1IMDSv2
Token requirementNo token is requiredA token is required when the instance is configured to require IMDSv2
Request patternDirect metadata GET requestsToken PUT, followed by token-bearing metadata GET requests
SSRF resistance characteristicsAn SSRF vulnerability may be able to issue direct metadata requestsThe token exchange adds a session requirement and makes many SSRF techniques harder
Recommended deployment postureUse only when legacy compatibility is necessary and risk is understoodRequire it for new and supported workloads
Compatibility considerationsWorks with older clientsOlder 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

SymptomLikely causeVerificationResolution
No role name returnedNo role or instance profile, association not updated, or wrong pathInspect the EC2 role association and request the role-listing path firstAssociate the intended instance profile and retry after the association updates
IMDSv1 request returns 401 UnauthorizedIMDSv2 is required, or a token is expired or invalidMake a new token PUT requestInclude the token header on every metadata GET
Token request failsEndpoint disabled, local firewall or namespace restriction, or unsuitable network pathCheck metadata options and test from the instance hostEnable the endpoint when appropriate and correct local network controls
SDK reports no credentialsNo role, unreachable metadata, proxy interference, or provider-chain overrideRun an IMDSv2 request locally; inspect proxy variables, profiles, and environment variablesRestore intended metadata access or remove the unintended credential override
AWS request is AccessDeniedRole lacks the action or resource permission, or another policy layer denies itRun aws sts get-caller-identity and review applicable policiesGrant the smallest required permission and investigate explicit denies
Container cannot access metadataHop limit, network rules, or an incorrect credential modelTest from the container and identify the orchestratorUse 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.