![](/img/trans.png)
[英]AWS Lambda calling another lambda and then parsing <botocore.response.StreamingBody problem
[英]Parsing Dictionary Response in AWS Lambda
我正在尝试创建一个 AWS Lambda 函数,该函数通过 S3 触发器使用 CloudTrail 事件。 此函数将在删除 CloudWatch 日志时发出警报。 事件:
“事件源”:“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")
这是我得到的结果:代码的结果
我的代码打印键/值用于调试目的。 任何想法为什么“DeleteLogStream”和“logs.amazonaws.com”值没有解析出来?
下面的示例 json 事件: https : //raw.githubusercontent.com/danielkowalski1/general-scripts/master/sampleevent
好的,解决了问题。 这会遍历整个 Records 列表,然后筛选每个列表值的字典,从而找到所有出现的“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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.