This repository has been archived by the owner on Aug 12, 2022. It is now read-only.
/
subscription_filter.py
99 lines (85 loc) · 3.28 KB
/
subscription_filter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import boto3
import json
import os
from botocore.vendored import requests
import string
def lambda_handler(event, context):
client = boto3.client('logs')
print ("subscription filter event: " + json.dumps(event))
# get environment variables
filterName = "ADSErrors"
destinationArn = os.environ['DestinationARN']
filterPattern = os.environ['FilterPattern']
logGroupNameList = event["ResourceProperties"]["LogGroupNames"]
response = {}
result = {
'Status': 'SUCCESS',
'Data': response,
'ResourceId': event["LogicalResourceId"]
}
if event["RequestType"] == "Create" or event["RequestType"] == "Update":
print ("destinationARN: " + destinationArn)
print ("filterPattern: " + filterPattern)
#iterate over the list of log groups and then put the subscription filter
try:
for logGroup in logGroupNameList:
print ("LogGroupName: " + logGroup)
response = client.put_subscription_filter(
logGroupName=logGroup,
filterName=filterName,
filterPattern=filterPattern,
destinationArn=destinationArn
)
except Exception as exp:
print("Exception: %s" % exp)
response = {"Exception": str(exp)}
result = {
'Status': 'FAILED',
'Data': response,
'ResourceId': event["LogicalResourceId"]
}
elif event["RequestType"] == "Delete":
#iterate over the list of log groups and then remove subscription filter
try:
print("Delete requested")
for logGroup in logGroupNameList:
response = client.delete_subscription_filter(
logGroupName=logGroup,
filterName=filterName
)
except Exception as exp:
print("Exception: %s" % exp)
response = {"Exception": str(exp)}
result = {
'Status': 'FAILED',
'Data': response,
'ResourceId': event["LogicalResourceId"]
}
send(event, context, result['Status'],
result['Data'], result['ResourceId'])
return
def send(event, context, responseStatus, responseData, physicalResourceId):
responseUrl = event['ResponseURL']
responseBody = {
'Status': responseStatus,
'Reason': 'See the details in CloudWatch Log Stream: ' + context.log_stream_name,
'PhysicalResourceId': physicalResourceId or context.log_stream_name,
'StackId': event['StackId'],
'RequestId': event['RequestId'],
'LogicalResourceId': event['LogicalResourceId'],
'Data': responseData
}
json_responseBody = json.dumps(responseBody)
print("Response body:\n" + json_responseBody)
headers = {
'content-type': '',
'content-length': str(len(json_responseBody))
}
try:
response = requests.put(responseUrl,
data=json_responseBody,
headers=headers)
print("Status code: " + response.reason)
except Exception as e:
print("send(..) failed executing requests.put(..): " + str(e))
return