lambda Python 小脚本

最近需要监控aws的instance创建,然后发送邮件。就写了一个小脚本来做这个事情。

如下:

# def lambda_handler(event, context):
    
#     # TODO implement
#     return 'Hello from Lambda'
    
# -*- coding: utf-8 -*-
# @Time    : 2018/7/6 13:13
# @Author  : liulei
# @File    : trail.py

import boto3,datetime,json

def lambda_handler(event, context):
    
    endtime = datetime.datetime.now()
    startime = datetime.datetime.now() + datetime.timedelta(minutes=-10)
    #startime = datetime.datetime.now() + datetime.timedelta(hours=-33)

    client = boto3.client('cloudtrail')
    client_sns = boto3.client('sns')
    response = client.lookup_events(
        LookupAttributes=[
            {
                'AttributeKey': 'EventName',
                'AttributeValue': 'RunInstances'
            },
        ],
        StartTime= startime.strftime("%Y-%m-%d %H:%M:00"),
        EndTime= endtime.strftime("%Y-%m-%d %H:%M:00"),
    )

    Event = response['Events']

    for i in Event:
        if "errorMessage" in i['CloudTrailEvent']:
            continue
        Instance = i['Resources']
        for instance_info in Instance:
            if instance_info['ResourceType'] == 'AWS::EC2::Instance':
                InstanceID = instance_info['ResourceName']
                username = i['Username']
                creattime = i['EventTime'].strftime("%Y-%m-%d %H:%M:%S")

                msg = '''系统检测到有新建实例,信息如下:
                实例创建用户: %s
                实例创建时间: %s
                实例ID      : %s
                ''' %(username,creattime,InstanceID)
                
                reson = client_sns.publish(
                    TopicArn='arn:aws-cn:sns:cn-north-1:900134215953:New_instance_alert',
                    Message=msg,
                )
            else:
                continue

该脚本配置在aws的lambda的函数上。通过cloud watch 来定时触发。给此函数授予 trail 、cloud watch、sns权限就可以了。

 

posted @ 2018-07-11 19:41  Star-Hitian  阅读(106)  评论(0)    收藏  举报