一、创建IAM策略
IAM->策略->创建策略->JSON
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:*" ], "Resource": "*" }, { "Effect": "Allow", "Action": "ec2:Describe*", "Resource": "*" }, { "Effect": "Allow", "Action": [ "ec2:CreateSnapshot", "ec2:DeleteSnapshot", "ec2:CreateTags", "ec2:ModifySnapshotAttribute", "ec2:ResetSnapshotAttribute" ], "Resource": [ "*" ] } ] }
二、创建角色
IAM->角色->创建角色->添加刚刚创建好的策略
三、添加标签
给每个正在运行的EC2实例都添加一个标签,值为自定义的实例名,后面python脚本会通过AWS API获取到这个值。
四、编辑Python3脚本,脚本名为“lambda_function.py”
import boto3 import datetime import os import pytz ec2 = boto3.resource('ec2') def lambda_handler(event, context): print("\n\nAWS snapshot backups starting at %s" % datetime.datetime.now()) instances = ec2.instances.filter( Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]) for instance in instances: instance_name = instance.tags[0]['Value'] for volume in ec2.volumes.filter(Filters=[{'Name': 'attachment.instance-id', 'Values': [instance.id]}]): description = '%s-%s-%s' % (instance_name, volume.volume_id, datetime.datetime.now().strftime("%Y%m%d")) # create ebs snaphost if volume.create_snapshot(VolumeId=volume.volume_id, Description=description): print("Snapshot created with description [%s]" % description) # delete expired snapshot for snapshot in volume.snapshots.all(): # expried datetime retention_days = 7 if datetime.datetime.now().replace(tzinfo=None) - snapshot.start_time.replace(tzinfo=None) > datetime.timedelta(days=retention_days): print("\t\tDeleting snapshot [%s - %s]" % ( snapshot.snapshot_id, snapshot.description )) snapshot.delete() print("\n\nAWS snapshot backups completed at %s" % datetime.datetime.now()) return True
五、打包python脚本以及需要的三方库(Python3)
# mkdir /tmp/lambda_tmp # mv lambda_function.py /tmp/lambda_tmp/ # pip install pytz -t /tmp/lambda_tmp/ # pip install boto3 -t /tmp/lambda_tmp/ # cd /tmp/lambda_tmp # zip -r9 ~/lambda_EBS.zip *
六、创建Lambda函数
Service->Lambda->创建函数
下一步,上传刚刚压缩好的zip包
下一步,添加CloudWatch触发器,定时一天运行一次
点击保存并测试,如果测试通过会返回True,点击Service->EC2->快照,你会发现已经在做EBS快照了。
原文地址:http://blog.51cto.com/daibaiyang119/2144485
时间: 2024-10-08 01:23:59