用于检查特定标签是不是不存在的 Lambda 函数-python

Posted

技术标签:

【中文标题】用于检查特定标签是不是不存在的 Lambda 函数-python【英文标题】:Lambda function to check if specific tag do NOT exists-python用于检查特定标签是否不存在的 Lambda 函数-python 【发布时间】:2018-11-22 05:03:13 【问题描述】:

我正在努力获得关注:

获取满足以下任一条件的所有 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 作为标签过滤器,因为您显然希望包含没有所有者标签的实例。然后你可以在返回的实例中查找没有所有者标签的实例。 我想返回 Owner=unknown 的实例和没有 Owner 标签的实例 【参考方案1】:

结合我的问题和@Rage 答案中的代码,我设法得到了我想要的

再次感谢愤怒!!

import boto3   
import collections     
import datetime     
import time     
import sys 

ses = boto3.client('ses')

email_from = 'Email'
email_to = 'Email'
email_cc = 'Email'
emaiL_subject = 'Subject'
email_body = 'Body'






ec = boto3.client('ec2', 'eu-west-1')     
ec2 = boto3.resource('ec2', 'eu-west-1')     
from datetime import datetime
from dateutil.relativedelta import relativedelta

#create date variables 

date_after_month = datetime.now()+ relativedelta(days=7)
#date_after_month.strftime('%d/%m/%Y')
today=datetime.now().strftime('%d/%m/%Y')






def lambda_handler(event, context): 
  #Get instances with Owner Taggs and values Unknown/known
    instance_ids = []
    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 or tags['Owner']=='unknown' or tags['Owner']=='Unknown':
              instance_ids.append(instance['InstanceId'])  

                #Check if "TerminateOn" tag exists:

              if 'TerminateOn' in tags:  
                  #compare TerminteOn value with current date
                    if tags["TerminateOn"]==today:

                    #Check if termination protection is enabled
                     terminate_protection=ec.describe_instance_attribute(InstanceId =instance['InstanceId'] ,Attribute = 'disableApiTermination')
                     protection_value=(terminate_protection['DisableApiTermination']['Value'])
                     #if enabled disable it
                     if protection_value == True:
                        ec.modify_instance_attribute(InstanceId=instance['InstanceId'],Attribute="disableApiTermination",Value= "False" )
                    #terminate instance 
                     ec.terminate_instances(InstanceIds=instance_ids)
                     print "terminated" + str(instance_ids)
                     #send email that instance is terminated

                    else: 
                    #Send an email to engineering that this instance will be removed X amount of days (calculate the date based on today's date and the termination date."

                      now=datetime.now()
                      future=tags["TerminateOn"]
                      TerminateOn = datetime.strptime(future, "%d/%m/%Y")
                      days= (TerminateOn-now).days
                      print str(instance_ids) +  " will be removed in "+ str(days) + " days"


              else: 
                 if not 'TerminateOn' in tags:#, create it  
                  ec2.create_tags(Resources=instance_ids,Tags=['Key':'TerminateOn','Value':date_after_month.strftime('%d/%m/%Y')])
                  ec.stop_instances(InstanceIds=instance_ids)

                  print "was shut down "+format(','.join(instance_ids))

【讨论】:

【参考方案2】:

就像我在评论中所说,您想放弃 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 的响应可能会分页,您也必须处理这个问题。

【讨论】:

以上是关于用于检查特定标签是不是不存在的 Lambda 函数-python的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 lambda 表达式检查元素是不是存在?

如何检查本地是不是存在带有特定标签的 Docker 镜像?

如何在编译时检查是不是存在可以使用特定参数集调用的函数?

检查是不是有任何标签具有特定的内部 HTML

使用 lambda boto3 检查 ec2 是不是存在

c# XDocument:检查特定节点名称是不是存在,如果不添加