Auto Delete Instance(EC2) AMI Using Lambda and Cloudwatch

In previous blog, We have learned "how to Automate EC2 AMI backup process". Today we will learn, how to delete old AWS Instance(EC2) AMI using Lambda and Cloudwatch with a retention period. So that we will not charged for old EC2 AMIs.

Please follow the below steps to achieve this.

Step 1: Create IAM policy for an IAM Role.

  • Copy the below policy and paste it in your IAM policy.
 1{
 2  "Version": "2012-10-17",
 3  "Statement": [
 4    {
 5      "Sid": "Stmt1563031869737",
 6      "Action": "ec2:*",
 7      "Effect": "Allow",
 8      "Resource": "*"
 9    }
10  ]
11}

Note: To know how to create a custom IAM policy , Please follow this link

Step 2: Create IAM Role and Attached the above IAM policy.

Note: To know how to create IAM Role, Please follow the this link

Step 3: Create Lambda Function.

  • To create an Lambda Function, Go to Lambda service from AWS console and create a new Function.
    Lambda Console
  • Add Lambda Function name. (You can write any name).
  • In Runtime info, Choose "Node.js".
  • In permission, Choose "Use an existing Role" in Execution Role
  • In Existing Role, choose the IAM role which you have create above for this Lambda Function.
  • Click on "Create Function".
  • Go to "Function Code" and Paste the below node.js code in it.
 1var aws = require('aws-sdk');  
 2aws.config.region = '#AWS-Region';  
 3var ec2 = new aws.EC2();  
 4var d = new Date();  
 5var x = #Retention-period-in-day;  /* ------ Retention (1 to X) Days ------- */  
 6d.setDate(d.getDate() - x);  
 7reqdate = d.toISOString().substring(0, 10);  
 8exports.handler = function(event, context) {  
 9ec2.describeImages({  
10    Owners: [
11        'self'
12    ],
13    Filters: [{
14        Name: 'tag:DeleteThisAMI',
15        Values: [
16            'yes'
17        ]
18    }]
19
20}, function(err, data) {
21    if (err) console.log(err, err.stack);
22    else {
23        for (var j in data.Images) {
24            imagename = data.Images[j].Name
25            imageid = data.Images[j].ImageId
26
27            if (imagename.indexOf(reqdate) > -1) {
28                console.log("AMI that is going to be deregistered: ", imagename);
29                console.log("AMI id: ", imageid);
30
31                var deregisterparams = {
32                    ImageId: imageid
33                };
34                ec2.deregisterImage(deregisterparams, function(err, data01) {
35                    if (err) console.log(err, err.stack);
36                    else {
37                        console.log("AMI has been Deregistered");
38
39                    }
40                });
41            }
42        }
43        setTimeout(function() {
44            for (var j in data.Images) {
45                imagename = data.Images[j].Name
46                if (imagename.indexOf(reqdate) > -1) {
47                    for (var k in data.Images[j].BlockDeviceMappings) {
48                        snap = data.Images[j].BlockDeviceMappings[k].Ebs.SnapshotId;
49                        console.log(snap);
50                        var snapparams = {
51                            SnapshotId: snap
52                        };
53                        ec2.deleteSnapshot(snapparams, function(err, data) {
54                            if (err) console.log(err, err.stack);
55                            else console.log("Attached Snapshot has been Deleted");
56                        });
57                    }
58                }
59            }
60        }, 10000);
61    }
62});
63}
  • Save the Lambda Function and Test the same. So that there should be no error.

Step 4: Create Cloudwatch Scheduler and attached the Lambda Function.

  • To configure the scheduler, Open CloudWatch Service and Click on the Rules menu, present in the Left side of your AWS console.

CloudWatch scheduler

  • Click in Create Rule and Select schedule from the Event Source.

CloudWatch Rule image

  • Select the Cron expression and Enter the Timing:

Here I want to take the AMI backup daily at 11:30 GMT Monday to Friday. (5:00 PM IST)

CloudWatch scheduler image

Note: Time in CloudWatch is in GMT. You have to check only to convert IST into GMT. You can use this link to convert the time from IST to GMT.

Also, Use this link to learn more about the CloudWatch cron format.

  • Select the Lambda function in Targets and select your function from the drop-down menu.

CloudWatch target

  • Last, enter the Rule name , the description and check the Enabled state check-box.

CloudWatch Last Step

  • Now Click on Create rule to complete the step.

CloudWatch Create Rule

Note: Please note all service should be in the same region.

Step 5: Shit relaxed, Your Scheduler will delete the AMI backup for you daily with X day retention.

I ❤ AWS! Happy Cloud Computing! 🧑‍💻 Enjoy #Cloudkaramchari