Let’s say, you have multiple Ec2 instances (about more than 50). Those are running for a different environment (development, staging and production) and you have decided to avoid disaster recovery- instance failure, accidentally termination and so on- for your instances. Therefore, it would be difficult to deal with all the instances such as making a manual backup and deleting older ones.
However, to avoid such problems, I have created an AMI automation script, which is completely run as a serverless (FAAS- function as a service). It will automatically create the AMI on behalf of you and will delete the older ones. In addition, It does not only save your efforts, time and cost, but it will also send the report of the script at the end such as newly created AMI id with respective instance id, deleted AMI id to SES.
Let’s create the automation in our AWS!
Step 1: Tag the instances
This script only lookout those instances which have a particular tag. For example, Key: BackupNode and value: True.
Thus, add the tag in all the instances for which you would like to run this script.
Step 2: Create an IAM role
We need to create an IAM role, which empowers the lambda function to access other services and perform the actions.
So, assign EC2, SES and CloudWatch logs full access policy to the role. Let’s take a look.
Step 3: Create a lambda function
In this step, we’ll create a lambda function and configure environment variables, memory and timeout period.
Next, just download the lambda code from the Github and install the external dependency(by executing `npm i` from the folder where package.json is placed), and upload it as a zip file on the lambda function.
Now, Let’s configure the environment variables in the lambda function.
Here, retentionType means time span(minutes, days, months, years, etc.) of the AMI and retentionTime entitles that the AMI will be eligible to delete after 5 minutes(or days, months, years, etc.).
Now, change the settings of the memory and timeout to avoid the performance issues of the lambda function.
Click on the save button on the top right and save it. Awesome!
Step 4: configure a cloudWatch event as a trigger of the lambda function
CloudWatch event will trigger the lambda function, which will be invoked.
Let’s create a cloudWatch event rule.
we have successfully configured a cloudWatch event with the lambda function.
Step 5: Configure SES service
In the SES (Simple Email Service), we need to verify the email addresses which we have configured in the lambda function as environment variables to receive a report of the script. Thus, verify your email addresses.
Congratulation! You have successfully created the serverless AMI automation script through lambda.
We have created a lambda function with an IAM role, a cloudwatch Event and a SES. Whenever the lambda function will be triggered by the cloudWatch Event, it will create AMI of the ec2 instances and delete the AMIs whose tagged expiry time is less than the current time.