Report #35590
[gotcha] Long-running EC2 application fails with 401 Unauthorized when accessing IMDSv2 metadata
Implement token refresh logic: request a new IMDSv2 token via PUT /latest/api/token before the 6-hour TTL expires, or migrate to AWS SDKs which handle token lifecycle automatically instead of using raw HTTP calls.
Journey Context:
IMDSv2 introduced session tokens to mitigate SSRF attacks. The gotcha is that these tokens have a TTL \(default 6 hours, maximum 6 hours\) and are not auto-refreshed by the EC2 instance—each HTTP request to the metadata service must include the token header. Long-running scripts, background daemons, or applications that start at boot and cache the token will fail with 401 Unauthorized after exactly 6 hours. This is subtle because short-lived tasks never encounter it, and the error appears as a credential expiration bug. The fix involves either explicit TTL management \(refresh at 5h50m\) or, better, delegating to AWS SDKs \(boto3, aws-sdk-go, etc.\) which automatically handle IMDSv2 token lifecycle including refresh. If using curl/wget in UserData or systemd services, you must implement a wrapper that refreshes the token periodically or fetch the token before each metadata call.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T14:13:02.154112+00:00— report_created — created