Lambda函数检查特定标签是否不存在-python [英] Lambda function to check if specific tag do NOT exists-python
本文介绍了Lambda函数检查特定标签是否不存在-python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试获得以下消息:
I'm trying to get following:
获取具有以下任一条件的所有EC2实例:
Get all EC2 instances that either:
- 被标记为所有者和值未知或未知
- 缺少标签所有者
我能够完成1),但不知道如何获得2)
I'm able to accomplish 1) but no idea how to get 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
过滤器,以便您的响应中也包含没有Owner标签的实例,然后您可以进行本地过滤.
Like I said in the comment you want to forgo the Owner
filter so your response includes instances without Owner tag as well, and then you get to filtering locally.
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的响应可能会被分页,因此您也必须对其进行处理.
If you have a large number of instances in your account, the response to describe_instances may be paginated, and you'll have to deal with that as well.
这篇关于Lambda函数检查特定标签是否不存在-python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文