简体   繁体   English

如何从实例内的 Python 获取 EC2 实例标签?

[英]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.我需要在 EC2 实例中获取 Python 中特定标签的值。

Restriction: Can't use the Python EC2 metadata module as “Tags allowed in metadata” won't be enabled.限制:不能使用 Python EC2 元数据模块,因为“元数据中允许的标签”将不会启用。

So I cannot do “ec2_metadata.tags[“Name”]” as that would throw an 404 error.所以我不能执行“ec2_metadata.tags[“Name”]”,因为这会引发 404 错误。

What other way can we do this?我们还有什么其他方法可以做到这一点? The curl method wouldn't work either since that also requires the metadata tags to be enabled. curl 方法也不起作用,因为这还需要启用元数据标签。

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.http://169.254.169.254/latest/meta-data/instance-id获取实例 ID,然后将describe_instances API 与实例 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.我确定还有其他解决方案,但由于我现在必须实施任何解决方案,就是这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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