【问题标题】:Get list of EC2 instances with specific Tag and Value in Boto3在 Boto3 中获取具有特定标签和值的 EC2 实例列表
【发布时间】:2018-06-12 20:00:38
【问题描述】:
如何使用 boto3 的标签和值过滤 AWS 实例?
import boto3
ec2 = boto3.resource('ec2')
client = boto3.client('ec2')
response = client.describe_tags(
Filters=[{'Key': 'Owner', 'Value': 'user@example.com'}])
print(response)
【问题讨论】:
标签:
python-3.x
amazon-web-services
amazon-ec2
scripting
boto3
【解决方案1】:
您使用了错误的 API。使用describe_instances
import boto3
client = boto3.client('ec2')
custom_filter = [{
'Name':'tag:Owner',
'Values': ['user@example.com']}]
response = client.describe_instances(Filters=custom_filter)
【解决方案2】:
有标签的实例和没有标签的实例可以如下检索
可以获取如下所有标签
import boto3
ec2 = boto3.resource('ec2',"us-west-1")
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
for instance in instances:
if instance.tags != None:
for tags in instance.tags:
if tags["Key"] == 'Name' or tags["Key"] == 'Owner':
if tags["Key"] == 'Name':
instancename = tags["Value"]
if tags["Key"] == 'Owner':
owner = tags["Value"]
else:
instancename='-'
print("Inastance Name - %s, Instance Id - %s, Owner - %s " %(instancename,instance.id,owner))
【解决方案3】:
boto3.client.describe_tags() 是通用的,但使用起来很乏味。因为您需要嵌套并指定要过滤的服务、标签键名和标签值。即
client = boto3.client('ec2')
filters =[
{'Name': 'resource-type', 'Values': ['instance']},
{'Name': 'Key', 'Values': ['Owner']},
{'Name': 'Values', 'Values' : ['user@example.com']}
]
response = client.describe_instances(Filters=filters)
正如@helloV 所建议的,使用 describe_instances() 会容易得多。
describe_tags 允许用户创建函数来遍历所有服务标签。