我尝试使用 EventBridge-Lambda-SNS 设置 EC2 启动/停止/重新启动电子邮件通知。因此,当 Cloudtrail 检测到 API RunInstances/StopInstances/RebootInstances 时,这将匹配 eventbridge 规则条件,该条件调用 lambda 函数通过 sns 主题发送自定义电子邮件正文。
功能代码:
import os
import json
import boto3
def lambda_handler(event, context):
EventID = event['detail']['eventID']
Account = event['account']
Timestamp = event['time']
Region = event['region']
InstanceID = event['detail']['requestParameters']['instancesSet']['items'][0]['instanceId']
EventName = event['detail']['eventName']
SourceIP = event['detail']['sourceIPAddress']
InitiatedBy = event['detail']['userIdentity']['arn']
if EventName == 'StopInstances':
msg_status = 'stopped'
elif EventName == 'StartInstances':
msg_status = 'started'
elif EventName == 'TerminateInstances':
msg_status = 'terminated'
body = f'Hi Team, \n\nThis is to inform you that EC2 instance with {InstanceID} is {msg_status}.Please find below information. \n\nEventID = {EventID}, \nAccount = {Account}, \nTimestamp = {Timestamp}, \nRegion = {Region}, \nInstanceID = {InstanceID}, \nEventName = {EventName}, \nSourceIP = {SourceIP}, \nInitiatedBy = {InitiatedBy} \n\nRegards,\nCloud Team'
sns_client = boto3.client('sns')
snsarn = os.environ['snsarn']
res = sns_client.publish(
TopicArn = snsarn,
Subject = f'Alert - {InstanceID} is {msg_status}',
Message = str(body)
)
然后我通过启动/停止实例测试了这个功能,并得到了预期的电子邮件正文。但除此之外,我在电子邮件中收到了我不想要的 Lambda 调用输出 JSON 内容。
预计:
Hi Team,
This is to inform you that EC2 instance with i-0d8219ba97c61c428 is started. Please find below information.
EventID = 9b07afa3-222c-4632-9dc9-bfa145ddb573,
Account = 12345678910,
Timestamp = 2023-08-13T04:49:49Z,
Region = us-east-1,
InstanceID = i-0d8219ba97c61c428,
EventName = StartInstances,
SourceIP = <IP>,
InitiatedBy = arn:aws:iam::12345678910:root
Regards,
Cloud Team
任何人都可以帮助我如何停止此活动吗? PFA 电子邮件截图。