Automate aws snapshot using Lambda and cloudwatch service

|
| By Webner

Automate the Snapshots using AWS Lambda & CloudWatch services.

Step.1 Create IAM Role with following accessibility

1. To get information of volumes and snapshots from EC2
2. To create new snapshots using the CreateSnapshot API call
In the AWS management console, go to IAM > Roles > Create New Role. Set name for role “automate-snapshots-role”.

Step.2 Attach permission policies

Step.3 Add tag for role (optional)

Step.4 Give name for new role and description for reference

Step.5 Role created

Step.6 Open Lambda

Step.7 Create a new function in Lambda

Step.8 Choose the Runtime to write your function and select the role created above.

Step.9 Function created

Step.10 Edit the code line and replace it with the code mentioned below.

# 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}])

Step.11 Save the code after replacing

Step.12 Verify the settings and make changes accordingly .

Step.13 Choose the VPC set, Subnets and security group for those volumes which need to auto snapshots and then click save button.

Step.14 Now saved function displayed.

Step.15 Now select the Cloudwatch events from left pane & then select lambda from right pane.

Step.16 Now we have configure the trigger or you can say cron job when to execute the created function.

Step.17 Create a new rule name as mentioned with (cloudwatch) permission set in existing role created above and give a brief description and choose the schedule expression.

Step.18 Now select the check box to enable the trigger.

Step.19 Now you see a message about the New trigger is having unsaved changes, so click save .

Leave a Reply

Your email address will not be published. Required fields are marked *