Dheeraj Choudhary
Dheeraj Choudhary's Blog

Dheeraj Choudhary's Blog

AWS Lambda & EventBridge | Find Unused AWS Elastic IP's In AWS Account On Weekly Basis And Notify Via Email

AWS Lambda & EventBridge | Find Unused AWS Elastic IP's In AWS Account On Weekly Basis And Notify Via Email

Dheeraj Choudhary
·Mar 22, 2022·

5 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Create SNS Topic And Subscribe
  • Create AWS Lambda Python Function To Find Unused AMI And Deregister it.
  • Using Amazon EventBridge Schedule Lambda On Weekly Basis
  • Resource Cleanup
  • Conclusion

In this blog we are going to check for list of Unused Elatic IP's on weekly basis and notify those Elastic Ip's from account using AWS Lambda function in python and AWS Eventbridge.

Create SNS Topic And Subscribe

  1. Open the Amazon SNS console, and then choose Topics from the navigation pane. image.png
  2. Choose Create topic. image.png
  3. For Name, enter a name for your topic[Notify-Unused-AMI]. image.png
  4. For Display name, enter a display name for your topic and choose create topic image.png
  5. After topic creation click on the Subscriptions tab, choose Create subscription. image.png
  6. For Protocol, choose Email -> For Endpoint, enter the email address where you want to receive the notifications -> Choose Create subscription. image.png image.png
  7. A subscription confirmation email is sent to the address you entered. Choose Confirm subscription in the email. image.png
  8. When you click on confirm you will get below message which confirms your subscription image.png
  9. Now go back to Topics->EC2-State-Change-Notify and you can see its status has changed from pending to confirmed. image.png Note the SNS topic ARN you created. You use this topic when creating the EventBridge rule.

Create AWS Lambda Python Function To Find Unused AMI And Deregister it.

  1. Goto Lambda console and click on create function image.png
  2. Select "Author From Scratch" , Function name = unused_ami, Runtime= Python and role we created with above policy attached to this blog and click on create function. image.png
  3. Goto code editor and start writing the code. image.png
  4. Python code in one module gains access to the code in another module by the process of importing it. The import statement combines two operations it searches for the named module, then it binds the results of that search to a name in the local scope.
    import boto3
    
  5. We will invoke the client for EC2
    client = boto3.client('ec2')
    
  6. First we will call describe_addresses() function to fetch list of all elastic ip addresses in our account and save the dictonary returned in variable, you can get the official documentation for this function here
    response = ec2.describe_addresses()
    
  7. Lets create empty list to save unused Elastic IP's which are not associated to instances.
     unused_eips = []
    
  8. First we will typecast response and save in variable to check if there is any existing elastic IP
    def lambda_handler(event, context):
     # First we will typecast response and save in variable to check if there is any existing elastic IP
     check = list(response['Addresses'])
     if not check:
         print("Elastic IP does not exist | Exiting program.....")
         exit()
    
  9. With above check it is confirmed that elastic ip exist on the account now we will traverse the response of describe_addresses() function which would be a dictonary. In this dictonary we will check if instance id is available. If its available that means elastic ip is assigned to this elastic ip

    def lambda_handler(event, context):
     # First we will typecast response and save in variable to check if there is any existing elastic IP
     check = list(response['Addresses'])
     if not check:
         print("Elastic IP does not exist | Exiting program.....")
         exit()
    
     # If address is available we will check if it is associated with instance or not
     for address in response['Addresses']:
         if 'InstanceId' in address:
             print('Elastic IP {} is associated with instance {}'.format(address['PublicIp'], address['InstanceId']))
    
  10. If instance id does not exist that means elastic ip is not associated. We will append these elastic ip's to list. This list we will use to send elastic ip's via email.

    def lambda_handler(event, context):
    # First we will typecast response and save in variable to check if there is any existing elastic IP
    check = list(response['Addresses'])
    if not check:
        print("Elastic IP does not exist | Exiting program.....")
        exit()
    
    # If address is available we will check if it is associated with instance or not
    for address in response['Addresses']:
        if 'InstanceId' in address:
            print('Elastic IP {} is associated with instance {}'.format(address['PublicIp'], address['InstanceId']))
        else:
            print('Elastic IP {} is unused and can be released'.format(address['PublicIp']))
            unused_eips.append("Unused elastic ip: {}".format(address['PublicIp']))
    
  11. Now we will use publish() function to send email with list of elastic ip and configure the email message and subject accordingly, you can get the official documentation for this function here
    for unused in unused_eips:
        sns_client.publish(
            TopicArn='<SNS Topic ARN>',
            Subject='Alert - Unused Elastic Ip To be dissociated',
            Message=str(unused)
        )
        return "success"
    
    To view entire github code please click here

Using Amazon EventBridge Schedule Lambda On Weekly Basis

  1. Open Amazon Eventbridge service and open rules. And click on create rule image.png
  2. Now we will create rule and schedule it. For scheduling you we will have to use cron expression as displayed below. You can find official documentation here image.png
  3. Now lets create our rule to start EC2 instance. First we will define name and description as below image.png
  4. Now we will define Cron job expression where we will define that this job should run on 11 am IST only on saturday . Expression would be
    0 11 ? * 7 *
    
    image.png
  5. Select target as the lambda function and select our lambda function to start EC2 instance and click on create. image.png

Resource Cleanup

  • Delete EventBridge Rule.
  • Delete Lambda
  • Delete SNS Topic
  • Delete Role Created for Lambda

Conclusion

In this blog we are going to check for list of Unused Elatic IP's on weekly basis and notify those Elastic Ip's from account using AWS Lambda function in python and AWS Eventbridge.

Stay tuned for my next blog.....

So, did you find my content helpful? If you did or like my other content, feel free to buy me a coffee. Thanks.

Did you find this article valuable?

Support Dheeraj Choudhary by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this