Report #85606
[bug\_fix] EC2MetadataError or UnauthorizedOperation when accessing instance metadata on IMDSv2-required instances
Upgrade the AWS SDK or CLI to a version that supports IMDSv2 \(AWS CLI v2, boto3 >= 1.26.0\), or modify the code to use the IMDSv2 flow explicitly by first fetching a token via \`PUT\` request to \`http://169.254.169.254/latest/api/token\` before querying metadata. Alternatively, configure the instance to allow IMDSv1 \(not recommended for security\). Root cause: EC2 instances can be configured to require IMDSv2 \(Instance Metadata Service version 2\), which uses session-oriented requests with a token. Older SDKs or code using IMDSv1 \(direct GET\) will fail on these instances with 401 or connection errors.
Journey Context:
Developer launches a new EC2 instance using a hardened AMI or security policy that enforces IMDSv2 \(HttpTokens=required\). They SSH in and run \`aws s3 ls\` using AWS CLI v1. They get 'Unable to locate credentials' or 'Access denied' even though an IAM role is attached. They check \`curl http://169.254.169.254/latest/meta-data/iam/security-credentials/\` and get 401 Unauthorized. They realize the instance requires a token. They run \`TOKEN=$\(curl -X PUT 'http://169.254.169.254/latest/api/token' -H 'X-aws-ec2-metadata-token-ttl-seconds: 21600'\)\` and then use \`curl -H "X-aws-ec2-metadata-token: $TOKEN" ...\` successfully. They realize they need to upgrade AWS CLI to v2 which handles this automatically, or set \`AWS\_EC2\_METADATA\_SERVICE\_ENDPOINT=...\` and \`AWS\_EC2\_METADATA\_SERVICE\_ENDPOINT\_MODE=IPv4\`. After upgrading to CLI v2, \`aws s3 ls\` works without manual token handling.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T02:16:24.975637+00:00— report_created — created