IMDSv2 and aws cli commands

0

We have a number of scripts written in BASH and Python that execute aws cli commands on the local host. For example one script runs the following: aws iam get-role --role-name But as I learned the hard way when we change over to IMDSv2 this command and many others breaks because the scripts are not getting the Tokens and using them in the request.

I am guessing that the aws cli v2 command get-access-token would return the IMDSv2 token. But then how would I use the token with the above command?

asked a year ago1808 views
1 Answer
1

With the introduction of IMDSv2 (Instance Metadata Service version 2) in AWS, there are changes to how EC2 instances fetch their instance metadata, which is often used to gather credentials for AWS CLI commands.

The key difference with IMDSv2 is that it requires a PUT request to get a token, which then must be provided in the GET request headers when you fetch metadata.

However, if your applications are using the AWS SDKs or CLI, then this switch should be mostly transparent because those libraries handle fetching credentials from the metadata service for you.

Here's how it works with AWS CLI: AWS CLI uses the AWS SDK for Python (Boto3). When you run a command, Boto3 tries to find credentials in a certain order, one of them being from the instance metadata. Boto3 will automatically handle token fetch and refresh for IMDSv2.

Therefore, there should not be any changes needed to your AWS CLI commands when moving from IMDSv1 to IMDSv2.

If you've run into issues, there may be other factors at play:

  • Check the version of your AWS CLI and Boto3. Make sure you are using a version that supports IMDSv2.
  • Look into IAM roles and policies. Are the roles that the instances are assuming have correct permissions?
  • Ensure that the EC2 instances are allowed to reach the instance metadata service. Some security measures might block or restrict this access.

If you really need to interact with instance metadata service directly in your scripts for some reason (which is not common), then you would use CURL or similar to make the PUT and GET requests, something like this:

TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"`
curl -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/

This is not generally needed for normal usage of the AWS CLI or SDKs, which handle this automatically.

profile picture
EXPERT
answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions