背景介紹:
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數量的變化: