在AWS Lambda中解析字典响应

时间:2018-12-21 03:03:22

标签: python python-3.x amazon-web-services aws-lambda amazon-cloudtrail

我正在尝试创建一个AWS Lambda函数,该函数通过S3触发器使用CloudTrail事件。此功能将在删除CloudWatch日志时发出警报。事件:

  

'eventSource':'logs.amazonaws.com'

  

'eventName':'DeleteLogStream'

需要作为同一事件一起找到。我有活动中的数据,但无法捕获和打印。

import boto3
import gzip
import json

SNS_TOPIC = "<SNS TOPIC ARN>"
SNS_SUBJECT = "<SUBJECT>"


s3_client = boto3.client('s3')
sns_client = boto3.client('sns')


def handler(event, context):
    for record in event['Records']:
        bucket = record['s3']['bucket']['name']
        key = record['s3']['object']['key']

    
    # Fetch logs from S3
    s3_object = s3_client.get_object(
        Bucket=bucket,
        Key=key,
    )

    # Extract file and metadata from gzipped S3 object
    with gzip.open(s3_object['Body'], 'rb') as binaryObj:
        binaryContent = binaryObj.read()
    
    # Convert from binary data to text
    raw_logs = binaryContent.decode()
    
    # Change text into a dictionary
    dict_logs = json.loads(raw_logs)
    

    # Make sure json_logs key 'Records' exists
    if 'Records' in dict_logs.keys():
    
        print("Printing Dictionary Content: {} \n\n".format(dict_logs))
        
	if dict_logs['Records'][0]['eventSource'] == 'logs.amazonaws.com' and dict_logs['Records'][0]['eventName'] == 'DeleteLogStream':
			print("Found DeleteLogStream event from logs.amazonaws.com!")
		
        # Print Key-Value pair for each item found
        for key, value in dict_logs['Records'][0].items():
            # Account for values that are also dictionaries
            if isinstance(value, dict):
                print("Parent Key: {}".format(key))
                for k, v in value.items():
                    print("Subdict Key: {}".format(k))
                    print("Subdict Value: {}".format(v))
                continue
            else:
                print("Key: {}".format(key))
                print("Value: {}".format(value))

        
        alert_message = "The following log was found: <extracted log contents here>"
        
        # Publish message to SNS topic
        sns_response = sns_client.publish(
            TopicArn=SNS_TOPIC,
            Message=alert_message,
            Subject=SNS_SUBJECT,
            MessageStructure='string',
        )

    else:
        print("Records key not found")

这是我得到的结果: Result from Code

我的代码打印键/值以进行调试。为何不解析“ DeleteLogStream”和“ logs.amazonaws.com”值的任何想法?

以下示例json事件: https://raw.githubusercontent.com/danielkowalski1/general-scripts/master/sampleevent

1 个答案:

答案 0 :(得分:1)

好的,解决了这个问题。这会遍历整个“记录”列表,然后筛选每个列表值的字典,从而找到所有出现的“ DeleteLogStream”。

EVENT_SOURCE = "logs.amazonaws.com"
EVENT_NAME = "DeleteLogStream"     

# Make sure 'Records'key exists
    if 'Records' in dict_logs.keys():
        for item in dict_logs['Records']:

            # Trigger only if a log
            if ('eventSource' in item):
                if (item['eventSource'] == EVENT_SOURCE):
                    if (item['eventName'] == EVENT_NAME):
                        # Grab other useful details for investigation
                        if item['sourceIPAddress']:
                            src_ip = item['sourceIPAddress']
                        if item['userIdentity']['arn']:
                            src_user = item['userIdentity']['arn']
相关问题