Brief intro to AWS IMDSv2

In a recent post I mentioned the AWS Instance Metadata Service (IMDS). It's the magic URL that allows an EC2 instance to retrieve all sorts of information related to itself including any temporary/on-demand credentials it may be entitled to. See the AWS docs to Work with instance metadata

You can use curl to poke around and see what's there. The following assumes IMDSv2. This should be your default as IMDSv1 has been deprecated due to security issues.

From a shell on the EC2 instance get an API token from the IMDS endpoint. This will return one that's good for one hour, plenty of time to kick tires.

TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 3600"`

You can then use that token, for the next hour, to poke about. e.g. to see the top of the meta-data tree run:

curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/

Here's an example from the system I mention in the post EC2 and Docker access to AWS services without embedded credentials. You don't need to supply credentials because the docker-credential-ecr-login helper application can retrieve them on demand. Assuming, of course, you've configured the roles and policies to permit that.

$ curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/
Instance-IAM-Role-Redacted

$ curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/Instance-IAM-Role-Redacted
{
  "Code" : "Success",
  "LastUpdated" : "2024-06-13T20:47:05Z",
  "Type" : "AWS-HMAC",
  "AccessKeyId" : "<redacted>",
  "SecretAccessKey" : "<redacted>",
  "Token" : "<redacted>",
  "Expiration" : "2024-06-14T02:48:22Z"
}