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?
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.
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:
export TOKEN=curl -X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" "http://169.254.169.254/latest/api/token"
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?