首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据标签名称过滤实例,并在Python中打印特定的标签值

根据标签名称过滤实例,并在Python中打印特定的标签值
EN

Stack Overflow用户
提问于 2019-05-29 19:07:12
回答 1查看 935关注 0票数 0

我想根据标签值过滤我的实例。这就完成了,我得到了每个实例的多个标记键和值。

代码:

代码语言:javascript
复制
client = boto3.client("ec2")
response = client.describe_instances(
    Filters=[
        {
            'Name': 'tag:Name',
            'Values': [
                'myapp-*'
            ]
        },
        {
            'Name': 'instance-state-name',
            'Values': [
                'running',
            ]
        }
    ]
)['Reservations']

for ec2_reservation in response:
    for ec2_instance in ec2_reservation["Instances"]:
       print(ec2_instance)

响应:(我故意删除了所有其他字段,并在下面只粘贴了标签部分)

代码语言:javascript
复制
'Tags': [{'Key': 'Patch group', 'Value': 'Amazon-Linux'},
          {'Key': 'Name', 'Value': 'myapp-mgmt-1'},
          {'Key': 'environment', 'Value': 'devl'},
          {'Key': 'ssm-managed', 'Value': 'true'},

'Tags': [{'Key': 'Patch group', 'Value': 'Amazon-Linux'},
          {'Key': 'Name', 'Value': 'myapp-web-1'},
          {'Key': 'environment', 'Value': 'devl'},
          {'Key': 'ssm-managed', 'Value': 'true'},

现在,当我尝试打印key-name的值时,我无法打印它。下面是我尝试过的。你能帮我解决这个问题吗。可能是重复的,但无法从其他帖子中找到适当的参考。

代码语言:javascript
复制
print(ec2_instance["Tags"][0][{'Name':'tag-key', 'Values':['Name']}])

TypeError: unhashable type: 'dict'

我期望得到如下输出:

代码语言:javascript
复制
'myapp-mgmt-1'
'myapp-web-1'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-11 23:36:09

过了一段时间,我想通了。下面是完整的代码供您参考:

注意:使用boto3.resource时,我必须在实例之间循环以获取它们的标记名。

代码语言:javascript
复制
client = boto3.client("ec2")
resource = boto3.resource("ec2")

response = client.describe_instances(
    Filters=[
        {
            'Name': 'tag:Name',
            'Values': [
                'myapp-*'
            ]
        },
        {
            'Name': 'instance-state-name',
            'Values': [
                'running',
            ]
        }
    ]
)['Reservations']

instanceList = []
for reservation in response:
    ec2_instances = reservation["Instances"]
    for instance in ec2_instances:
        InstanceId = (instance['InstanceId'])
        #InstanceState = (instance['State']['Name'])
        #InstanceLaunchTime = (instance['LaunchTime'])

        ec2instance = resource.Instance(InstanceId)
        InstanceName = []
        for tags in ec2instance.tags:
            if tags["Key"] == 'Name':
                InstanceName = tags['Value']

        fInstance = (InstanceName, InstanceId)
        InstanceDetails = (",".join(fInstance))
        instanceList.append(fInstance)

print(json.dumps(instanceList, indent=4))

到目前为止,这对我来说是可行的。如果你有更好的办法,请告诉我。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56359143

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档