Home > Net >  How to get EC2 instance tags from Python within the instance?
How to get EC2 instance tags from Python within the instance?

Time:08-29

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.

CodePudding user response:

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.

CodePudding user response:

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.

  • Related