1
votes

I'm new to Python and programing. I need to create a Lambda function using Python 3.7 that will look for a specific tag/value combo and return the tag value along with the instance id . I can get both with my current code but I'm having a hard time figuring out how to combine these. boto3.resource gives me the tag value and boto3.client gives me the instance id.

I have EC2 instances (1000's) where we need to monitor the tag value for the tag 'expenddate' and compare the value (mm/dd/yy) to the current date (mm/dd/yy) and alert when 'expenddate' value is less than the current date.


    import boto3
    import collections
    import datetime
    import time
    import sys

    from datetime import date as dt

    def lambda_handler(event, context):
        today = datetime.date.today()
        mdy = today_string = today.strftime('%m/%d/%y')
        ec2 = boto3.resource('ec2')
        for instance in ec2.instances.all():
            if instance.tags is None:
                continue
            for tag in instance.tags:
                if tag['Key'] == 'expenddate':
                    if (tag['Value']) <= mdy:
                        print ("Tag has expired!!!!!!!!!!!")
                    else:
                        print ("goodby")
        client = boto3.client('ec2')
        resp = client.describe_instances(Filters=[{
            'Name': 'tag:expenddate',
            'Values': ['*']
        }])

        for reservation in resp['Reservations']:
            for instance in reservation['Instances']:
                print("InstanceId is {} ".format(instance['InstanceId']))

I want to end up with a combined instance id and tag value or two variables that I can combine later.

1

1 Answers

1
votes

change

print ("Tag has expired!!!!!!!!!!!")

to

# initialise array 
expiredInstances=[]
.
.
.
.
.
print ("%s has expired" % instance.id)
expiredInstances.append({'instanceId':instance.id,'tag-value':tag['Value']})

That will give you an array of instanceId's with tag values