AWS Lambda - Copy EC2 Snapshot automatically between regions
There are many ways to copy EC2 snapshot from one region to another region.
What is AWS Lamda function?
AWS Lambda is a compute service that lets you run code without provisioning or managing servers. AWS Lambda executes your code only when needed and scales automatically, from a few requests per day to thousands per second.
Following is the code to copy EC2 snapshots using AWS Lamda from region one to region two.
Below AWS Lamda function will describe all EC2 snapshots, which has tag key as city, and copy all snapshots from US East (N. Virginia) – [us-east-1] to Asia Pacific (Singapore) [ap-southeast-1] region.
import boto3
client = boto3.client('ec2')
def lambda_handler(event, context):
response = client.describe_snapshots(
Filters=[
{
'Name': 'tag-key',
'Values': [
'city',
]
},
]
)
for snapshot in response["Snapshots"]:
snapshot_id = snapshot["SnapshotId"]
copy_snapshot(snapshot_id, 'us-east-1', 'ap-southeast-1')
def copy_snapshot(snapshot_id, source_region, destination_region):
print "Started copying.. snapshot_id: " + snapshot_id + ", from: " + source_region + ", to: " + destination_region
res = client.copy_snapshot(SourceSnapshotId=snapshot_id,
SourceRegion=source_region,
DestinationRegion=destination_region)
if res["HTTPStatusCode"] == 200:
print "Successfully copyied.. snapshot_id: " + snapshot_id + ", from: " + source_region + ", to: " + destination_region
else:
print "Failed to copy.. snapshot_id: " + snapshot_id + ", from: " + source_region + ", to: " + destination_region