代码之家  ›  专栏  ›  技术社区  ›  Milister

lambda函数检查特定标记是否不存在python

  •  2
  • Milister  · 技术社区  · 6 年前

    我正试着得到以下信息:

    获取以下所有EC2实例:

    1. 使用标记所有者和值unknown或unknown标记
    2. 缺少标记所有者

    我能做到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)))
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   RaGe    6 年前

    就像我在评论中说的你想放弃 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"
    

    如果您的帐户中有大量实例,则描述实例的响应可能会分页,您还必须处理该问题。

        2
  •  0
  •   Milister    6 年前

    把我的问题和“愤怒的回答”的代码结合起来,我终于得到了我想要的

    再次感谢愤怒!!

    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))