Automating Snapshot Creation

Lab Steps

lock
Logging in to the Amazon Web Services Console
lock
Creating a AWS Lambda Function That Takes EBS Snapshots
lock
Testing the AWS Lambda function
lock
Automating Snapshot Creation
Need help? Contact our support team

Here you can find the instructions for this specific Lab Step.

If you are ready for a real environment experience please start the Lab. Keep in mind that you'll need to start from the first step.

Introduction

In this step, you will automate the snapshots' creation by creating a Lambda function that will retrieve the Volume IDs and create a CloudWatch Event to schedule the function.

 

Instructions

1. Return to the Lambda Console, and click Create function in the upper-right corner:

alt

The new function will get all of the Volume IDs of the EBS volumes that exist.

 

2. As you did before, ensure Author from scratch is selected and enter the following values in the bottom form:

  • NameGetVolumeIds
  • Runtime: Select Node.js 12.x

alt

 

3. Under Permissions, click Change default execution role and select the following:

  • Execution roleUse an existing role
  • Existing role: Select role beginning with cloudacademylabs-EBSLambdaRole

 

4. Click Create function.

 

5. Scroll down to the Code source section, double-click the Index.js file, and overwrite the contents with the following code:

Copy code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
"use strict";
console.log("Loading function");
var AWS = require("aws-sdk");
var ec2 = new AWS.EC2({ region: "us-west-2" });
var lambda = new AWS.Lambda();

exports.handler = (event, context, callback) => {
  ec2.describeVolumes(null, function (err, data) {
    if (err) {
      console.log(err, err.stack);
      callback(err, err.stack);
    } else {
      for (var i = 0; i < data.Volumes.length; i++) {
        var params = {
          FunctionName: "TakeEbsSnapshot", //Or the name of the function you created
          Payload: JSON.stringify({ volume: data.Volumes[i].VolumeId }),
          LogType: "Tail",
        };

        lambda.invoke(params, function (err, data) {
          if (err) {
            console.log(err, err.stack);
            callback(err, err.stack);
          } else {
            console.log(data);
          }
        });
      }
    }
  });
};

Your Code source section will look like this:

alt

This function will gets the volume IDs (ec2.describeVolumes on line 8) and calls the first Lambda function to take the snapshot of each volume (lambda.invoke on line 20). The parameters (params on passed to the first Lambda include the Payload that specifies the volume ID (data.Volumes[i].VolumeId on line 16) and the function name (FunctionName on line 15) of the first Lambda function. If you have used a different name than TakeEbsSnapshot, you need to specify the function name that you used.

 

6. To change the timeout of the function, click the Configuration tab, and click Edit.

The Basic settings form will load.

 

7. Set the Timeout to 10 seconds, and click Save at the bottom:

alt

The function's timeout needs to be increased because there are several snapshots that will be taken and three seconds is not enough to complete the function.

 

8. To deploy your function, click the Code tab, and click Deploy.

 

9. To create a new test event, click Test at the top of the Code source section:

alt

 

10. In the Configure test event form, enter the following values into the form:

  • Event nameTestSnapshots
  • Event body: Enter the following JSON into the event editor at the bottom of the form
    Copy code
    {
    }

alt

The function doesn't require any event data, so an empty JSON object is used ({}).

 

11. Scroll to the bottom and click Create.

 

12. To test your function with the test event you created, click Test again:

alt

A few seconds later, you will a successful result in the Execution results tab:

alt

In this case, no callback is set so there is no result response and null is shown. However, if you look at the code, you can see that in the parameters that are used to call the other Lambda function, the LogType is set to Tail:

Copy code
1
2
3
4
5
 var params = {
   FunctionName: 'TakeEBSSnapshot', //Or the name of the function you created
   Payload: '{"volume": "' + data.Volumes[i].VolumeId + '"}',
   LogType: 'Tail'
 }; 

That tells the Lambda service to send the callback of the TakeEbsSnapshot function to the logs of the GetVolumeIDs function. That is why you can see the Payload entries in the Log output for each call of TakeEbsSnapshot. 

The test succeeded so you will now schedule the function to execute daily.

 

13. In the Function overview section, click on Add triggers, and select EventBridge (CloudWatch Events):

alt

 

14. Under Rule, select Create a new rule.

 

15. Enter the following form values:

  • RuleMonitorMyWebsiteTask
  • Schedule expression: rate(1 minute)

alt

16. Scroll to the bottom and click Add to complete adding the trigger.

You will see a notification that the trigger has been added.

 

17. Click the Code tab and click Deploy to save the new function configuration.

All of the volumes will now have a snapshot taken every minute.

 

Summary

In this Lab Step, you automated the creation of snapshots by creating another Lambda function and using CloudWatch Event to schedule the function every minute.


Challenge (Optional)

Now that you have successfully automated the EBS snapshot creation process using Lambda and CloudWatch events, you can make some improvements to the code if you have time remaining in your Lab session. For example, try to refactor the GetVolumeIDs function to show all the snapshots that were created in the Execution Result.