AWS Lambda & EventBridge | Find Unused AWS Elastic IP's In AWS Account On Weekly Basis And Notify Via Email
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
- Open the Amazon SNS console, and then choose Topics from the navigation pane.
- Choose Create topic.
- For Name, enter a name for your topic[Notify-Unused-AMI].
- For Display name, enter a display name for your topic and choose create topic
- After topic creation click on the Subscriptions tab, choose Create subscription.
- For Protocol, choose Email -> For Endpoint, enter the email address where you want to receive the notifications -> Choose Create subscription.
- A subscription confirmation email is sent to the address you entered. Choose Confirm subscription in the email.
- When you click on confirm you will get below message which confirms your subscription
- Now go back to Topics->EC2-State-Change-Notify and you can see its status has changed from pending to confirmed. 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.
- Goto Lambda console and click on create function
- 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.
- Goto code editor and start writing the code.
- 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
- We will invoke the client for EC2
client = boto3.client('ec2')
- 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()
- Lets create empty list to save unused Elastic IP's which are not associated to instances.
unused_eips = []
- 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()
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']))
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']))
- 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
To view entire github code please click herefor unused in unused_eips: sns_client.publish( TopicArn='<SNS Topic ARN>', Subject='Alert - Unused Elastic Ip To be dissociated', Message=str(unused) ) return "success"
Using Amazon EventBridge Schedule Lambda On Weekly Basis
- Open Amazon Eventbridge service and open rules. And click on create rule
- 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
- Now lets create our rule to start EC2 instance. First we will define name and description as below
- 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 *
- Select target as the lambda function and select our lambda function to start EC2 instance and click on create.
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.