【问题标题】:Sending alerts when an instance is created inside AWS在 AWS 中创建实例时发送警报
【发布时间】:2017-07-31 11:56:17
【问题描述】:

当有人在 AWS 中创建 EC2 实例时需要接收电子邮件。我曾尝试使用 cloudwatch,但这似乎对我不起作用。它说数据不足。有没有更好的方法?

Creating CloudWatch Alarms for CloudTrail Events

【问题讨论】:

标签: amazon-web-services amazon-s3 amazon-ec2 cloud amazon-cloudwatch


【解决方案1】:

Step1:创建 Cloud watch Rule 以通知创建。根据按下 lauch 按钮时 EC2 实例的生命周期。实例从 Pending 状态变为 Running 状态。所以创建待处理状态的规则

Create a Cloud watch Rule as specified in the image screenshot

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  

  }
  }
}

Step3 : 创建通知的 SNS 主题

Step4 : 编写一个 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,
    }

注意:如果实例从停止状态更改为运行状态,此代码会触发通知。

【讨论】:

    猜你喜欢
    • 2016-10-03
    • 2018-01-08
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 2020-10-20
    • 2018-11-06
    相关资源
    最近更新 更多