Running Terraform from an EC2 with IMDSv2 Enabled

Good Afternoon,

I am trying to run terraform on an ec2 instance with IMDSv2. In order to do so I have to get the instance profile role from metadata. Is there a clean way of doing that with v2 enabled or do I need to write something to get the token and then apply it to the api calls?

Good Morning (writing from GMT+13 :D),

I don’t recall something special is needed. Have you tried to run AWS CLI and see how it goes? aws sts get-caller-identity without a default profile or AWS SDK environment variable set should return the role and validate the credentials.

Same with Terraform, it should just try to query IMDS to get credentials (https://registry.terraform.io/providers/hashicorp/aws/latest/docs#ec2-instance-metadata-service) and it is supposed to work regardless of the version of IMDS API.

Yes, if I run the CLI against an ec2 instance with IMDSv1 it works just as expected. If I run the commands against v2 I get a 401 unauthorized until I run the following commands:

  1. export TOKEN=curl -X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" "http://169.254.169.254/latest/api/token"

  2. curl -H “X-aws-ec2-metadata-token:$TOKEN” -v “http://169.254.169.254/latest/meta-data

The token’s existence is required by the v2 spec.

If you have a program using an up to date AWS SDK, this is taken care of for you (AWS SDK have been updated to work with v2 - as document here Configure the instance metadata service - Amazon Elastic Compute Cloud). I believe Terraform has a recent enough version so that it just works. What version of Terraform are you using?