AWS Lambda(三)---用lambda和cloudwatch创建EBS Snapshots

背景介绍:

lambda的功能,类似脚本,在lambda页面添加trigger组件,意味着可以监听这个组件的通知或者入参,然后调用lambda的代码做事。

本文的例子是:lambda函数实现的功能是,给本region内的所有ec2做备份,也就是snapshot。

cloudwatch的作用是,监控某个组件的变化,监测到变化后可调用lambda做出相应的变动。这里cloudwatch没有监控别的组件,而是设置了一个定时任务,也就是每1分钟 或者2分钟 就通知lambda函数跑一边代码。本例子 rule a是1分钟一次的定时任务,也就是一分钟通知lambda跑一次。rule b是2分钟跑一次。然后打开ec2页面,查看snapshot是否按照这个频率变多。

1.创建一个lambda function,选择python语言。在function code区域,内容写为:

import json
import boto3

# Setting ec2 client.
ec2 = boto3.client('ec2')

# Our lambda handler function!
def lambda_handler(event, context):
    # Printing event received.
    # print("Received event: " + json.dumps(event, indent=2))

    # Let's go ahead and print the rule arn to the logs so we know they are different!
    rule_name = event['resources']
    print(rule_name)

    # Setting the variable to loop through later.
    # Filtering by only looking for 'in-use' EBS volumes.
    total_ebs = ec2.describe_volumes(Filters=[{'Name': 'status', 'Values': ['in-use']}])

    # Looping through and collecting all EBS volumes.
    for volume in total_ebs['Volumes']:
    	# Creating the snaphsot for all volumes within our region.
        ec2.create_snapshot(VolumeId=volume['VolumeId'],Description=volume['Attachments'][0]['InstanceId'])

        print("All done with volume: " + volume['VolumeId'])

页面上方新建测试文本,测试内容写为:

{
  "version": "0",
  "id": "89d1a02d-5ec7-412e-82f5-13505f849b41",
  "detail-type": "Scheduled Event",
  "source": "aws.events",
  "account": "123456789012",
  "time": "2016-12-30T18:44:49Z",
  "region": "us-east-1",
  "resources": [
    "arn:aws:events:us-east-1:123456789012:rule/LinuxAcademyRules"
  ],
  "detail": {}
}

具体步骤不会,可以参考https://blog.csdn.net/daiqinge/article/details/103283484

2. lambda的designer区域,增加一个trigger,选择cloudwatch event, 然后点击页面上方的save保存。

3. 创建一个rule,起名为ruleA,其中schedule expression内容写为: rate(1 minute)

enable这个rule,save了,再跑去ec2页面观察 snapshot的变化,可以看到以1分钟的频率一直在增多。

4. 在搜索cloudwatch的首页,进入后,选择新建rule,名字叫为 rule b

选择schedule,设置频率为2分钟,配置如下:

设置name为ruleb

5. 回到lambda页面,可以看到有两个rules,你可以一次enable一个rule,然后跑去ec2页面的snapshot页面看 volume snapshot数量的变化:

发布了140 篇原创文章 · 获赞 80 · 访问量 36万+

猜你喜欢

转载自blog.csdn.net/daiqinge/article/details/103306979