简体   繁体   中英

How to get EC2 instance tags from Python within the instance?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM