Lambda/Python-Boto3: Copy multiple snapshots to another backup AWS account

Nowadays, I am juggling with Python-Boto3/Lambda. I have found many good posts to create/delete EBS snapshots using Lambda but didn’t find any post to copy multiple snapshots to another backup AWS account which comes under AWS best practices, hence I am writing this post with a thought that it will be definitely helpful.

Please follow below blog which having lambda scripts to create/delete EBS snapshots.

http://blog.powerupcloud.com/2016/02/15/automate-ebs-snapshots-using-lambda-function/

Below Boto3 script assumes that you already have TAGGED in your snapshots which you want to copy to another AWS account. In this example, I have chosen the tag “DeleteOn:*”.

Note: I am using 111111111111 as a source AWS account and 222222222222 as Target AWS account.

Here we go:-

import boto3
import os
ec2 = boto3.resource(‘ec2’)
client = boto3.client(‘ec2’)
response = client.describe_snapshots(
OwnerIds=[
‘111111111111’,
],
Filters=[
{
‘Name’: ‘tag-key’,
‘Values’: [ ‘DeleteOn’, ]
},
{
‘Name’: ‘tag-value’,
‘Values’: [ ‘*’, ]
},
],
MaxResults=10
)
snapshots = response[‘Snapshots’]
for snapshot in snapshots:
#print snapshot[‘SnapshotId’]
snap = snapshot[‘SnapshotId’]
a = ec2.Snapshot(snap)
b = a.modify_attribute(
Attribute=’createVolumePermission’,
OperationType=’add’,
UserIds=[
‘111111111111’,
],
CreateVolumePermission={
‘Add’: [
{
‘UserId’: ‘222222222222’,
},
],
}
)

Some important troubleshooting points :

  1. Use botocore version 1.4.70, if you will find below error while executing above script.

botocore.exceptions.DataNotFoundError: Unable to load data for: ec2/2016–09–15/service-2

2. How to install botocore particular version?

# pip install botocore==1.4.70

3. Same script you can run in AWS Lambda. Just need to add below lines on top of the code.

def lambda_handler(event, context):

print event.keys()

Rest all code will be same.

Hope it will be useful !! :)

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.