
[英]Trying to Filter on 'Not tagged' AND 'Empty value' EC2 instances while using Boto3 in Lambda and then shut them down
[英]send email whenever ec2 is shut down using serverless
我是无服务器框架和AWS的新手,我需要在python上创建一个lambda函数,该函数将在ec2关闭时发送电子邮件,但我真的不知道如何使用无服务器。 因此,如果有人可以帮助我做到这一点,或者至少给我一些帮助,请开始。
您可以为此使用CloudWatch。
您可以创建一个cloudwatch规则
然后使用SNS目标传递电子邮件。
您想要的是CloudWatch Event 。
简而言之,CloudWatch事件能够触发Lambda函数并将其传递如下:
{
"version": "0",
"id": "123-456-abc",
"detail-type": "EC2 Instance State-change Notification",
"source": "aws.ec2",
"account": "1234567",
"time": "2015-11-11T21:36:16Z",
"region": "us-east-1",
"resources": [
"arn:aws:ec2:us-east-1:12312312312:instance/i-abcd4444"
],
"detail": {
"instance-id": "i-abcd4444",
"state": "shutting-down"
}
从那里,您可以在Lambda上运行的Python代码中解析此信息。 要获取关闭实例的实例ID,您将使用以下代码:
instance_id = event["detail"]["instance-id"]
然后,您可以在官方boto3库的帮助下使用Amazon SES(简单电子邮件服务)API并发送电子邮件。 请参阅: http : //boto3.readthedocs.io/en/latest/reference/services/ses.html#SES.Client.send_email
当然,您还需要具有适当特权的适当IAM角色,才能使用附加到Lambda函数的SES。 您可以在AWS IAM角色页面上轻松创建一个新角色。
对于初学者来说,乍一看似乎不胜枚举:
使用无服务器,您可以像这样为您的函数定义事件触发器...
functions:
shutdownEmailer:
handler: shutdownEmailer.handler
events:
- cloudwatchEvent:
event:
source:
- "aws.ec2"
detail-type:
- "EC2 Instance State-change Notification"
detail:
state:
- shutting down
enabled: true
然后,您可以期望每次事件发生时都会调用您的lambda。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.