Aws automatic snapshot using lambda

Lambda offers the ability to execute "serverless" code which means that AWS will provide the run-time platform for us. It currently supports the following languages: Node.js, Java, C#, and Python

Create IAM Role

we need to create an IAM role that has permissions to do the following

*In the AWS management console, we'll go to IAM > Roles > Create New Role. We name our role "ebs-snapshots-role".

For Role Type, we select AWS Lambda. This will grant the Lambda service permissions to assume the role.


On the next page, we won't select any of the managed policies so move on to the Next Step. Go back to the Roles page and select the newly created role. Under the Permissions tab, you'll find a link to create a custom inline policy.

Paste the JSON below for the policy.

{

    "Version": "2012-10-17",

    "Statement": [

        {

            "Effect": "Allow",

            "Action": [

                "logs:*"

            ],

            "Resource": "arn:aws:logs:*:*:*"

        },

        {

            "Effect": "Allow",

            "Action": "ec2:Describe*",

            "Resource": "*"

        },

        {

            "Effect": "Allow",

            "Action": [

                "ec2:CreateSnapshot",

                "ec2:DeleteSnapshot",

                "ec2:CreateTags",

                "ec2:ModifySnapshotAttribute",

                "ec2:ResetSnapshotAttribute"

            ],

            "Resource": [

                "*"

            ]

        }

    ]

}


Create Snapshots Function in Lambda

we can move on to writing the code to create snapshots.In the Lambda console, go to Functions -> Create a Lambda Function -> Configure function and paste the code below into the code pane

# Backup all in-use volumes in all regions

import boto3

def lambda_handler(event, context):

    ec2 = boto3.client('ec2'

    # Get list of regions

    regions = ec2.describe_regions().get('Regions',[] )

    # Iterate over regions

    for region in regions:

        print "Checking region %s " % region['RegionName']

        reg=region['RegionName']

        # Connect to region

        ec2 = boto3.client('ec2', region_name=reg)

        # Get all in-use volumes in all regions  

        result = ec2.describe_volumes( Filters=[{'Name': 'status', 'Values': ['in-use']}])

        for volume in result['Volumes']:

            print "Backing up %s in %s" % (volume['VolumeId'], volume['AvailabilityZone'])

            # Create snapshot

            result = ec2.create_snapshot(VolumeId=volume['VolumeId'],Description='Created by Lambda backup function ebs-snapshots'

            # Get snapshot resource 

            ec2resource = boto3.resource('ec2', region_name=reg)

            snapshot = ec2resource.Snapshot(result['SnapshotId'])

            volumename = 'N/A'

            # Find name tag for volume if it exists

            if 'Tags' in volume:

                for tags in volume['Tags']:

                    if tags["Key"] == 'Name':

                        volumename = tags["Value"]

            # Add volume name to snapshot for easier identification

            snapshot.create_tags(Tags=[{'Key': 'Name','Value': volumename}])

The code will create snapshots for any in-use volumes across all regions.It will also add the name of the volume to the snapshot name tag so it's easier for us to identify whenever we view the list of snapshots.

Next, select the role we created in the Lamba function handler and role section. The default timeout for Lambda functions is 3 seconds, which is too short Let's increase the timeout to 1 minute under Advanced Settings.    This will give our function enough time to kick off the snapshot process for each volume.

Click Next then Create Function on the review page to finish.

Recent Comments

No comments

Leave a Comment