Skip to content Skip to sidebar Skip to footer

Lambda Function To Check If Specific Tag Do Not Exists-python

I'm trying to get following: Get all EC2 instances that either: are Tagged with tag Owner and value Unknown or unknown are missing tag Owner I'm able to accomplish 1) but no

Solution 1:

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"

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.

Solution 2:

Combining code from my question and @Rage answer i managed to get what i want

Thanks again 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')






deflambda_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']
        ifnot'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 dateif 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 itif 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 terminatedelse: 
                    #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
                      printstr(instance_ids) +  " will be removed in "+ str(days) + " days"else: 
                 ifnot'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))

Post a Comment for "Lambda Function To Check If Specific Tag Do Not Exists-python"