Skip to content

Instantly share code, notes, and snippets.

@clarkdave
Created June 29, 2017 22:27
Show Gist options
  • Save clarkdave/c11dcaa201ce52dc1000c583a84f457f to your computer and use it in GitHub Desktop.
Save clarkdave/c11dcaa201ce52dc1000c583a84f457f to your computer and use it in GitHub Desktop.
(AWS Lambda) Send ECS Task events to CloudWatch Logs
# This lambda function can be linked with CloudWatch events to send Task state changes to
# a CloudWatch Logs stream
#
# This is highly recommended as, in my experience, the API does *NOT* return all state change
# events; this is the only way to reliably see them all
import os
import time
import json
import boto3
def handler(event, context):
if event['source'] != 'aws.ecs':
raise ValueError("Function only supports input from events with a source type of: aws.ecs")
group = ''
stream = ''
if event['detail-type'] == 'ECS Task State Change':
group = os.environ['TASK_EVENTS_GROUP']
stream = event['detail']['group'].replace(':', '/') + '/' + event['detail']['taskArn'].split('/')[1]
else:
raise ValueError("Only Task State Change events are supported")
client = boto3.client('logs')
response = client.describe_log_streams(logGroupName=group,logStreamNamePrefix=stream)
logStreams = response['logStreams']
sequenceToken = None
if logStreams:
logStream = logStreams[0]
if 'uploadSequenceToken' in logStream:
sequenceToken = logStream['uploadSequenceToken']
else:
client.create_log_stream(logGroupName=group,logStreamName=stream)
logEvents = [
{
'timestamp': int(round(time.time() * 1000)),
'message': json.dumps(event)
},
]
if sequenceToken:
client.put_log_events(
logGroupName=group,
logStreamName=stream,
sequenceToken=sequenceToken,
logEvents=logEvents
)
else:
client.put_log_events(logGroupName=group, logStreamName=stream, logEvents=logEvents)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment