Create Instance(EC2) AMI Auto Backup Using Lambda and Cloudwatch

Today we will create an AWS Instance(EC2) AMI backup using Lambda and Cloudwatch. So that we can automate the AMI creation process as per our requirement.

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 Attach 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 now = new Date();  
 5date = now.toISOString().substring(0, 10)  
 6hours = now.getHours()  
 7minutes = now.getMinutes()  
 8exports.handler = function(event, context) {  
 9    var instanceparams = {
10        Filters: [{
11            Name: 'tag:#tag-name',		/*  Add tag-name of AWS Instance  */
12            Values: [
13                '#tag-value'	/*  Add tag-value of tag-name of that AWS Instance  */
14            ]
15        }]
16    }
17    ec2.describeInstances(instanceparams, function(err, data) {
18        if (err) console.log(err, err.stack);
19        else {
20            for (var i in data.Reservations) {
21                for (var j in data.Reservations[i].Instances) {
22                    instanceid = data.Reservations[i].Instances[j].InstanceId;
23                    nametag = data.Reservations[i].Instances[j].Tags
24                    for (var k in data.Reservations[i].Instances[j].Tags) {
25                        if (data.Reservations[i].Instances[j].Tags[k].Key == 'Name') {
26                            name = data.Reservations[i].Instances[j].Tags[k].Value;
27                        }
28                    }
29                    console.log("Creating AMI of the Instance: ", name);
30                    var imageparams = {
31                        InstanceId: instanceid,
32                        Name: name + "_" + date + "_" + hours + "-" + minutes,
33                        NoReboot: true
34                    }
35                    ec2.createImage(imageparams, function(err, data) {
36                        if (err) console.log(err, err.stack);
37                        else {
38                            image = data.ImageId;
39                            console.log(image);
40                            var tagparams = {
41                                Resources: [image],
42                                Tags: [{
43                                    Key: 'DeleteThisAMI',
44                                    Value: 'yes'
45                                }]
46                            };
47                            ec2.createTags(tagparams, function(err, data) {
48                                if (err) console.log(err, err.stack);
49                                else console.log("Tags added to the created AMIs");
50                            });
51                        }
52                    });
53                }
54            }
55        }
56    });
57}
  • 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 take the AMI backup for you daily at given Timing.

To learn who to delete AWS AMI after retention period over. Click on this link.

Enjoy :)