Search code examples
pythonamazon-web-servicesamazon-ec2boto3

Get Instance 'Name' Tag via Python script once IMDSv2 is enabled


I would like to understand how to fetch an EC2's 'Name' tag value once version 2 of the Instance Metadata Service is enforced over version 1.

When I tried to describe_instances under an ec2 client via boto3 my requests returned access denied.

I created the following code to access an EC2's metadata:

        http_headers = { 'X-aws-ec2-metadata-token-ttl-seconds': 600, "content-type": "application/json"}
        instance_details = None

        connection = httplib.HTTPConnection('http://169.254.169.254')
        connection.request('PUT', '/latest/api/token', None, http_headers)

        response = connection.getresponse()
        auth_token = response.read()

        http_headers = {'X-aws-ec2-metadata-token': auth_token, "content-type": "application/json"}

        connection.request('GET', '/2016-06-30/dynamic/instance-identity/document/', None, http_headers)
        response = connection.getresponse()

        instance_details = response.read()

This of course allows me to attain the instance Id, region, etc. but I need a way to get the set of tags associated with an instance.

I haven't seen a way to add a token to a boto3 client. If anyone knows a work around please let me know.

Thanks!


Solution

  • The Access Denied error indicates that AWS has rejected your call to DescribeInstances().

    If an IAM Role has been assigned to the instance, then add the ec2:DescribeInstances permission to the IAM Role. The Amazon EC2 Instance Metadata Service will be used to retrieve credentials for IAM Role.

    If you are using credentials from an IAM User, the add the permission to that IAM User.

    Tags are not provided by the Instance Metadata service.