根据标记名筛选实例,并在Python中打印特定的标记值

2024-03-29 07:39:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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

代码:

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)

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

^{pr2}$

现在,当我试图打印键名的值时,我做不到。下面是我尝试过的。你能帮我解决这个问题吗。可能被复制,但无法从其他帖子中找到合适的参考。在

print(ec2_instance["Tags"][0][{'Name':'tag-key', 'Values':['Name']}])

TypeError: unhashable type: 'dict'

我希望输出为:

'myapp-mgmt-1'
'myapp-web-1'

Tags: 实例instance代码namein标记clientfor
1条回答
网友
1楼 · 发布于 2024-03-29 07:39:20

过了一段时间我就明白了。以下是完整的代码供您参考:

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

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))

到目前为止,这对我很有效。如果你有更好的办法,请告诉我。在

相关问题 更多 >