[英]Sending alerts when an instance is created inside AWS
有人在AWS中创建EC2实例时需要接收电子邮件。 我曾尝试过使用cloudwatch,但这似乎对我不起作用。 它说数据不足。 有更好的方法吗?
步骤1:创建Cloud Watch规则以通知创建。 根据EC2实例的生命周期(按下lauch按钮)。 实例从Pending状态变为Running状态。 因此,创建待处理状态规则
Step2:创建一个Step函数。 因为Cloud Trail将所有事件记录在帐户中的时间至少要延迟20分钟。 如果要创建实例的用户名,此步骤功能很有用。
{
"StartAt": "Wait",
"States": {
"Wait": {
"Type": "Wait",
"Seconds": 1800,
"Next": "Ec2-Alert"
},
"Ec2-Alert":{
"Type": "Task",
"Resource":"arn:aws:lambda:ap-south-1:321039853697:function:EC2-Creation-Alert",
"End": true
}
}
}
第三步:创建一个用于通知的SNS主题
步骤4:编写一个lambda函数,以从云径中获取日志并获取创建实例的用户名。
import json
import os
import subprocess
import boto3
def lambda_handler(event, context):
client = boto3.client('cloudtrail')
client1 = boto3.client('sns')
Instance=event["detail"]["instance-id"]
response = client.lookup_events(
LookupAttributes=[
{
'AttributeKey': 'ResourceName',
'AttributeValue': Instance
},
],
MaxResults=1)
test=response['Events']
st="".join(str(x) for x in test)
print(st)
user=st.split("Username")[1]
finalname=user.split(",")
Creator=finalname[0]
#print(st[st.find("Username")])
Email= "Hi All ,\n\n\n The User%s has created new EC2-Instance in QA account and the Instance id is %s \n\n\n Thank you \n\n\n Regard's lamda"%(Creator,Instance)
response = client1.publish(
TopicArn='arn:aws:sns:ap-south-1:321039853697:Ec2-Creation-Alert',
Message=Email
)
# TODO implement
return {
'statusCode': 200,
}
注意:如果实例从停止状态更改为运行状态,此代码将触发通知。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.