我创建了一个AWS Lambda函数,以便在EC2实例更改状态时发送警报邮件(SNS),这非常正常 . 我这样做是通过在cloudWatch中创建一个规则来触发我的lambda函数并捕获所有实例细节并发布SNS来发送邮件 .
Current Feature: 1.触发点 - 实例状态的变化2. Lambda触发 - 捕获实例状态(运行/停止)3 . Lambda发布SNS邮件 - Mail有关于所有EC2实例的实例状态详细信息(运行/停止),甚至是实例国家没有改变 .
Required Feature: 1.触发点 - 实例状态的变化2. Lambda触发 - 捕获实例状态(运行/停止)3 . Lambda发布SNS邮件 - Mail应该仅发送有关ec2实例的实例状态详细信息(运行/停止)改变 .
提前致谢!
Lambda Code:
import boto3
import json
import logging
import datetime
import os
from botocore.exceptions import ClientError
from datetime import timedelta
region ='us-east-1'
ec2 = boto3.resource('ec2',region)
client = boto3.client('ec2',region)
snsClient = boto3.client('sns',region)
def lambda_handler(event, context):
global stop
global start
stop = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}])
start = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
for instance1 in stop:
print('Ec2 Instances which are stopped: ', 'Instance ID: ', instance1.id, 'Instance state: ', instance1.state, 'Instance type: ',instance1.instance_type)
for instance2 in start:
print('Ec2 Instances which are running: ', 'Instance ID: ', instance2.id, 'Instance state: ', instance2.state, 'Instance type: ',instance2.instance_type)
publish_sns()
def publish_sns():
print('Publish Messsage to SNS Topic')
subject_str = 'Alert! EC2 Instances Started / Stopped'
affected_instances1 = [instance1.id for instance1 in stop]
affected_instances2 = [instance2.id for instance2 in start]
DT = datetime.datetime.now() + timedelta(hours = 5.5)
Waqt = DT.strftime("%Y-%m-%d %H:%M:%S")
msg = '^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nHello Team, \n\nFollowing EC2 instances have been started / stopped: \n\nStopped instances: \n'+ str(affected_instances1)+ '\n\nStarted instances: \n'+str(affected_instances2)+'\n\nInstance state changed time IST: '+str(Waqt)+'\n\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^'
response = snsClient.publish(TopicArn=os.environ['SNSARN'],Message=msg,Subject=subject_str)
1 回答
您的lambda使用两个参数调用 - 事件和上下文 - 您应该使用事件,因为它包含有关EC2实例更改的信息,而不是查询ec2.instance,它将始终返回所有实例而不管其状态更改 .
无论您的实现如何 - 您所描述的是能够知道所有实例的先前状态并在发送电子邮件之前过滤未更改的实例 . 您可以将整个数组保存到数据库,并在状态更改调用lambda时将其进行比较 .