Using Notifications to Trigger AWS Lambda
实验目标
实验目标
- 配置一个auto Scaling 去触发notification
- 创建一个Lambda去响应 notification
实验目标架构

关键流程说明
- 一个Auto scaling group已经被配置好了;
- 将通过创建一个EC2实例来触发auto scaling服务来线性扩展;
- 这个将触发一个SNS(Amazon Simple Notification Service Topic);
- 这个SNS TOPIC会触发一个AWS Lambda函数,这个函数将会:
- 创建一个EBS volumes snapshot,绑定到EC2实例上
- 给实例增加一个tag
- 将log信息发送到 AWS的CloudWatch logs上
操作步骤
创建一个SNS Topic
- 用途:用来接收Auto Scaling Group的提醒;
- 创建:点击菜单创建一个SNS topic,名字设置为ScaleEvent
配置 Auto Scaling 去发送事件通知
- 用途:当创建一个新的EC2实例到指定的Group中,自动触发一个通知到SNS
- 操作方式:选择EC2标签,选择到Auto Scaling Group,选择已经创建好的那个Auto Scaling Group:1
- 点击notification配置项,创建一个新的notification,对于“send notification to”这个标签,选择接收队列是ScaleEvent;
- 设置 只有“lannch(启动)”这个动作会触发通知;并保存;
创建一个IAM角色“Snap_and_Tag”,为了Lambda函数执行使用
- 用途:用于Lambda调用S3、DynamoDB等托管服务进行操作时的权限
- 操作方式:选择创建角色,选择场景是Lambda,权限设置选择“AmazonEC2FullAccess“、”AWSLambdaExecute”;
创建一个Lambda函数
-
用途:用于执行给新增的实例增加一个snapshot volume
image.png
-
配置信息参考如下
image.png
这里选择了执行语言是python2.7,同时执行的角色是刚才创建的Snap_and_Tag
- 设置执行的python代码块
# Snap_and_Tag Lambda function
#
# This function is triggered when Auto Scaling launches a new instance.
# A snapshot of EBS volumes will be created and a tag will be added.
from __future__ import print_function
import json, boto3
def lambda_handler(event, context):
print("Received event: " + json.dumps(event, indent=2))
# Extract the EC2 instance ID from the Auto Scaling event notification
message = event['Records'][0]['Sns']['Message']
autoscalingInfo = json.loads(message)
ec2InstanceId = autoscalingInfo['EC2InstanceId']
# Snapshot all EBS volumes attached to the instance
ec2 = boto3.resource('ec2')
for v in ec2.volumes.filter(Filters=[{'Name': 'attachment.instance-id', 'Values': [ec2InstanceId]}]):
description = 'Autosnap-%s-%s' % ( ec2InstanceId, v.volume_id )
if v.create_snapshot(Description = description):
print("\t\tSnapshot created with description [%s]" % description)
# Add a tag to the EC2 instance: Key = Snapshots, Value = Created
ec2 = boto3.client('ec2')
response = ec2.create_tags(
Resources=[ec2InstanceId],
Tags=[{'Key': 'Snapshots', 'Value': 'Created'}]
)
print ("***Tag added to EC2 instance with id: " + ec2InstanceId)
# Finished!
return ec2InstanceId
这个脚本主要完成如下动作:从SNS中获取EC2实例的ID,创建一个snapshot,同时绑定到EC2上,给EC2创建一个Tag标识snapshot已经创建
- 填写function的基本信息
Description:Snapshot and tag EC2 instance
timeout:3 min 0 sec - 添加触发器
在触发器页面选择 SNS,设置SNS topic:ScaleEvent - 保存Lambda函数,此时SNS触发的内容已经编写完成;
扩展Auto Scaling Group来触发函数
- 用途:通过扩展Auto Scaling Group来触发SNS,通过SNS的notification来调用 Lambda函数,创建Snapshot,并绑定到新增的EC2实例上
- 操作方式:选择EC2菜单,只需要更改Auto Scaling组的desired 数值即可,这里设置成“2”,这样就可以自动增加实例了。
- 查看过程:通过查看activity history的tab标签页面,查看状态,等到新的实例扩展完毕,我们可以查验 snapshot是否已经创建。
- 校验snapshot创建:通过点击snapshot查看是否已经创建了,并且了解tagname的是否已经被打上标签;
网友评论