我正在尝试以下内容:
获取满足以下任一条件的所有 EC2 实例:
- 被标记为标签所有者和值未知或未知
- 缺少标签所有者
我能够完成 1) 但不知道如何实现 2)
import boto3
import collections
import datetime
import time
import sys
ec = boto3.client('ec2', 'eu-west-1')
ec2 = boto3.resource('ec2', 'eu-west-1')
def lambda_handler(event, context):
instance_ids = []
reservations = ec.describe_instances(
Filters=[
{'Name': 'tag:Owner', 'Values': ['Unknown', 'unknown']},
]
).get('Reservations', [])
for reservation in reservations:
instances = reservation['Instances']
for instance in instances:
instance_ids.append(instance['InstanceId'])
print("Stopping instances: {}".format(','.join(instance_ids)))
就像我在评论中说的,你想放弃Owner
过滤,以便您的响应也包含没有所有者标签的实例,然后您可以在本地进行过滤。
reservations = ec.describe_instances().get('Reservations', [])
for reservation in reservations:
for instance in reservation['Instances']:
tags = {}
for tag in instance['Tags']:
tags[tag['Key']] = tag['Value']
if not 'Owner' in tags:
print instance['InstanceId'] + " does not have Owner tag"
elif tags['Owner'] in ['Unknown', 'unknown']:
print instance['InstanceId'] + " has [U|u]nknown Owner tag"
如果您的帐户中有大量实例,对describe_instances 的响应可能会分页,您也必须处理这个问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)