注意:虽然可以使用lambda自动备份快照,但是现在推荐使用Lifecycle Policy,设置比较方便,也不需要部署脚本,只需要在卷创建时添加一个backup标签即可。
代码如下:
import boto3
import time
def lambda_handler(event, context):
ec2 = boto3.client(‘ec2’, region_name=‘eu-central-1’)
# Get all in-use volumes in the region
result = ec2.describe_volumes( Filters=[{'Name': 'status', 'Values': ['in-use']}])
for volume in result['Volumes']:
for i in volume['Tags']:
if i["Key"] == "Name":
if 'prd' in i['Value'] or 'prod' in i['Value']:
# if 'prd' in volume['Tags'][0]['Value'] or 'prod' in volume['Tags'][0]['Value']:
# Create snapshot
print "Backing up %s in %s" % (volume['VolumeId'], volume['AvailabilityZone'])
time.sleep(3)
action = ec2.create_snapshot(VolumeId=volume['VolumeId'],Description='(Frankfurt time zone) Created by Lambda backup function')
# Get snapshot resource
ec2resource = boto3.resource('ec2', region_name='eu-central-1')
snapshot = ec2resource.Snapshot(action['SnapshotId'])
volumename = 'N/A'
when = time.strftime("%Y%m%d-%H%M")
# 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}])
snapshot.create_tags(Tags=[{'Key': 'Date','Value': when}])