skip to Main Content

I need to get the value for a particular tag in Python within an EC2 instance.

Restriction: Can’t use the Python EC2 metadata module as “Tags allowed in metadata” won’t be enabled.

So I cannot do “ec2_metadata.tags[“Name”]” as that would throw an 404 error.

What other way can we do this? The curl method wouldn’t work either since that also requires the metadata tags to be enabled.

2

Answers


  1. Chosen as BEST ANSWER

    My solution:

    region = ec2_metadata.region
    instance_id = ec2_metadata.instance_id
    ec2_resource = boto3.resource(‘ec2’,region_name=region)
    ec2_instance = ec2_resource.Instance(instance_id)
    tags = ec2_instance.tags
    

    Then I get the value for a particular tag by:

    for tag in tags:
        if tag[“Key”] == “Name”:
            print(tag[“Value”])
    

    I’m sure there are other solutions but since I had to implement any solution for now, this is it.


  2. Get the instance ID from http://169.254.169.254/latest/meta-data/instance-id, then use the describe_instances API with the instance id.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search