Lambda,AWS和Python的自动化管理操作 - 自动创建快照,删除快照

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lambda,AWS和Python的自动化管理操作 - 自动创建快照,删除快照相关的知识,希望对你有一定的参考价值。

这一节看看如何通过boto3来管理EC2的快照。在实际生产环境中,豆子使用的是AWS提供的解决方案 EBS Snapshot Scheduler, 直接导入Cloudformation的stack,会自动配置Lambda函数和DynamoDB数据库,然后我们可以通过标签来进行设置。从学习的角度,我们直接来弄一个超简易的版本。我们可以直接写两个Lambda函数,一个进行创建,一个进行删除。

首先,设置一个tag标签

技术图片

接下来创建Lambda函数

技术图片

IAM Role的配置如下

{
  "Version": "2012-10-17",
  "Statement": [{
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "ec2:CreateSnapshot",
        "ec2:CreateTags",
        "ec2:DeleteSnapshot",
        "ec2:Describe*",
        "ec2:ModifySnapshotAttribute",
        "ec2:ResetSnapshotAttribute"
      ],
      "Resource": "*"
    }
  ]
}

具体函数如下所示:

from datetime import datetime

import boto3

def lambda_handler(event, context):

    ec2_client = boto3.client(‘ec2‘)

        #获取所有region的名字
    regions = [region[‘RegionName‘]
               for region in ec2_client.describe_regions()[‘Regions‘]]

        #循环每一个region,找到所有标签了backup的实例
    for region in regions:

        print(‘Instances in EC2 Region {0}:‘.format(region))
        ec2 = boto3.resource(‘ec2‘, region_name=region)

        instances = ec2.instances.filter(
            Filters=[
                {‘Name‘: ‘tag:backup‘, ‘Values‘: [‘true‘]}
            ]
        )

                #获取时间戳
        # ISO 8601 timestamp, i.e. 2019-01-31T14:01:58
        timestamp = datetime.utcnow().replace(microsecond=0).isoformat()

                #对每一个实例的每一个volume,都创建一个快照
        for i in instances.all():
            for v in i.volumes.all():

                desc = ‘Backup of {0}, volume {1}, created {2}‘.format(
                    i.id, v.id, timestamp)
                print(desc)

                snapshot = v.create_snapshot(Description=desc)

                print("Created snapshot:", snapshot.id)

然后在Cloudwatch里面设置一个计划任务,定期执行这个函数

技术图片

这个是绑定了Role和触发器的示意图

技术图片

执行之后,可以查看快照
技术图片

在Cloudwatch里面查看print的输出日志,可以看见成功执行了

技术图片

同样的方式,我们可以创建一个Lambda函数来删除快照
技术图片

具体的函数如下:


import boto3

def lambda_handler(event, context):

    #sts 返回的是一个字典,通过get获取当前账号的ownerId,如果失败则返回None
    account_id = boto3.client(‘sts‘).get_caller_identity().get(‘Account‘)

    ec2 = boto3.client(‘ec2‘)
    """ :type : pyboto3.ec2 """
    regions = [region[‘RegionName‘]
               for region in ec2.describe_regions()[‘Regions‘]]

    for region in regions:
        print("Region:", region)
        ec2 = boto3.client(‘ec2‘, region_name=region)
        """ :type : pyboto3.ec2 """
        response = ec2.describe_snapshots(OwnerIds=[account_id])

        snapshots = response["Snapshots"]
        print(snapshots)

        #Snapshot 是一个很长的列表,每个元素是一个字典结构;sort指定通过时间来排序
        #下面等同于
        # def sortTime(x):
        #     return x["StartTime"]
        # snapshots.sort(key=sortTime)

        # Sort snapshots by date ascending
        snapshots.sort(key=lambda x: x["StartTime"])

        # Remove snapshots we want to keep (i.e. 3 most recent)
        snapshots = snapshots[:-3]

        for snapshot in snapshots:
            id = snapshot[‘SnapshotId‘]
            try:
                print("Deleting snapshot:", id)
                ec2.delete_snapshot(SnapshotId=id)
            except Exception as e:
                print("Snapshot {} in use, skipping.".format(id))
                continue

同样可以创建计划任务执行函数

技术图片

执行之后CloudWatch里面的print日志
技术图片

以上是关于Lambda,AWS和Python的自动化管理操作 - 自动创建快照,删除快照的主要内容,如果未能解决你的问题,请参考以下文章

Lambda,AWS和Python的自动化管理操作 - 自动开机和关机

AWS Lambda 自动化和 PowerShell

AWS Lambda 自动化和 Python - 自动创建S3 Bucket lifecycle

在python中自动测试aws lambda函数

AWS攻略——使用CodeBuild进行自动化构建和部署Lambda(Python)

AWS攻略——使用CodeBuild进行自动化构建和部署Lambda(Python)