1、建立IAM策略
python
IAM->策略->建立策略->JSON
ide
{ "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": [ "*" ] } ] }
2、建立角色函數
IAM->角色->建立角色->添加剛剛建立好的策略測試
3、添加標籤ip
給每一個正在運行的EC2實例都添加一個標籤,值爲自定義的實例名,後面python腳本會經過AWS API獲取到這個值。it
4、編輯Python3腳本,腳本名爲「lambda_function.py」
pip
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: for item in instance.tags: if item["Key"] == "Name": instance_name = item["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
5、打包python腳本以及須要的三方庫(Python3)io
# 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 *
6、建立Lambda函數event
Service->Lambda->建立函數function
下一步,上傳剛剛壓縮好的zip包
下一步,添加CloudWatch觸發器,定時一天運行一次
點擊保存並測試,若是測試經過會返回True,點擊Service->EC2->快照,你會發現已經在作EBS快照了。