1. 程式人生 > >使用AWS Lambda自動定時快照EBS卷

使用AWS Lambda自動定時快照EBS卷

imp delet def watch host %s date create creat

一、創建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快照了。

使用AWS Lambda自動定時快照EBS卷