AWS Lambda-create标记(如果不存在)

时间:2018-06-12 21:27:16

标签: python amazon-web-services amazon-ec2 aws-lambda

对于每个AWS区域

1.获取所有

的EC2实例

2.are标记为标记所有者和值未知或未知

3.缺少标签所有者

对于每个EC2实例

4.检查实例是否有标签" Terminate_On"

其他

5.用标签" Terminate_On"标记实例。和从现在起7天后的日期值。

步骤1,2和3已完成:

import boto3   
import collections     
import datetime     
import time     
import sys 
from datetime import datetime
from dateutil.relativedelta import relativedelta

ec = boto3.client('ec2', 'eu-west-1')     
ec2 = boto3.resource('ec2', 'eu-west-1')     
date_after_month = datetime.now()+ relativedelta(days=7)
#print date_after_month.strftime('%d/%m/%Y')  

def lambda_handler(event, context):  

    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:
                a =  instance['InstanceId'] + " does not have Owner tag"
            elif tags['Owner'] in ['Unknown', 'unknown']:
                b = instance['InstanceId'] + " has [U|u]nknown Owner tag"
            if not 'TerminateOn' in tags:  
                ec2.create_tags(
                    Resources=[instance['InstanceId']],
                    Tags= [{
                        'Key':'TerminateOn', 
                        'Value':date_after_month.strftime('%d/%m/%Y')}])  
            #print a+" "+b

4.对于从上面的代码返回的实例(带有所有者标签的实例和没有所有者标签的实例)检查Terminate_On标签是否存在

5.如果不是,请将date_after_month.strftime('%d/%m/%Y')作为值

创建该标记

问题出在第5步,如果一个EC2实例正在运行,没有问题,标签已创建,但如果有多个,则仅为第一个创建标记

显示以下错误:

for tag in instance['Tags']:
KeyError: 'Tags'

1 个答案:

答案 0 :(得分:0)

完整的解决方案:

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