[英]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.