使用AWS Lambda自动定时快照EBS卷

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->角色->建立角色->添加刚刚建立好的策略测试

1.PNG


3、添加标签ip

给每一个正在运行的EC2实例都添加一个标签,值为自定义的实例名,后面python脚本会经过AWS API获取到这个值。image.pngit

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

image.png

下一步,上传刚刚压缩好的zip包

image.png

下一步,添加CloudWatch触发器,定时一天运行一次

lambda-event-schedule

image.png

点击保存并测试,若是测试经过会返回True,点击Service->EC2->快照,你会发现已经在作EBS快照了。

相关文章
相关标签/搜索