我想根据标签值过滤我的实例。这就完成了,我得到了每个实例的多个标记键和值。
代码:
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)响应:(我故意删除了所有其他字段,并在下面只粘贴了标签部分)
'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的值时,我无法打印它。下面是我尝试过的。你能帮我解决这个问题吗。可能是重复的,但无法从其他帖子中找到适当的参考。
print(ec2_instance["Tags"][0][{'Name':'tag-key', 'Values':['Name']}])
TypeError: unhashable type: 'dict'我期望得到如下输出:
'myapp-mgmt-1'
'myapp-web-1'发布于 2019-06-11 23:36:09
过了一段时间,我想通了。下面是完整的代码供您参考:
注意:使用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))到目前为止,这对我来说是可行的。如果你有更好的办法,请告诉我。
https://stackoverflow.com/questions/56359143
复制相似问题