Configuring the Lambda Function
To configure the Lambda function, create an AWS Lambda Function that triggers the processing from CloudWatch Events to CloudWatch Logs.
Ensure that you have completed the following tasks:
Creating an IAM role for the Lambda function
Creating a Lambda function
Creating a CloudWatch events rule
- Go to your AWS Lambda console.
- Open the configuration section of your Lambda function. Click Create function.
- If CloudWatch Events is not automatically added as a trigger source, then add it. The Designer tab appears:
- On the Function code pane, replace the default code in
lambda_function.py
with the following Python code:import boto3 import time import json print('Loading function') def lambda_handler(event, context): cloudwatch_events = boto3.client('events') cloudwatch_logs = boto3.client('logs') logGroupFullName='GuardDutyLogGroup' logStreamFullName='GuardDutyLogStream' #Try to get LogStream description, if error found create the log group and log stream try: response = cloudwatch_logs.describe_log_streams(logGroupName=logGroupFullName, logStreamNamePrefix=logStreamFullName) except: cloudwatch_logs.create_log_group(logGroupName=logGroupFullName) cloudwatch_logs.create_log_stream(logGroupName=logGroupFullName,logStreamName=logStreamFullName) response = cloudwatch_logs.describe_log_streams(logGroupName=logGroupFullName, logStreamNamePrefix=logStreamFullName) pass record=json.dumps(event) logStreams = response ['logStreams'] #Try to read logStream description, if error found create the logStream and read the description again try: logStream = logStreams[0] except: cloudwatch_logs.create_log_stream(logGroupName=logGroupFullName,logStreamName=logStreamFullName) response = cloudwatch_logs.describe_log_streams(logGroupName=logGroupFullName, logStreamNamePrefix=logStreamFullName) logStream = logStreams[0] pass token= None if 'uploadSequenceToken' in logStream: token = logStream['uploadSequenceToken'] #if sequenceToken is available use it to post new log to CloudWatch, otherwise post without sequenceToken optional parameter if token: response = cloudwatch_logs.put_log_events( logGroupName=logGroupFullName, logStreamName=logStreamFullName, logEvents=[ { 'timestamp': int(round(time.time() * 1000)), 'message': record }, ], sequenceToken=token ) else: response = cloudwatch_logs.put_log_events( logGroupName=logGroupFullName, logStreamName=logStreamFullName, logEvents=[ { 'timestamp': int(round(time.time() * 1000)), 'message': record }, ] ) return {'records': record}
- Click Save.