-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathCloudWatch2S3-additional-account.template
249 lines (217 loc) · 8.21 KB
/
CloudWatch2S3-additional-account.template
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
Description: Continuously dump all matching CloudWatch Log groups to a bucket in a
central account for long-term storage (by CloudSnorkel)
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: Target
Parameters:
- LogDestination
- Label:
default: CloudWatch Logs
Parameters:
- SubscribeSchedule
- LogGroupNamePrefix
ParameterLabels:
LogDestination:
default: Log Destination
LogGroupNamePrefix:
default: Required Log Group Name Prefix
SubscribeSchedule:
default: Look for New Logs Schedule
AWS::ServerlessRepo::Application:
Author: CloudSnorkel
Description: Logging source for CloudWatch2S3 from a separate AWS account. Deploy
CloudWatch2S3 to your main account first.
HomePageUrl: https://github.com/CloudSnorkel/CloudWatch2S3
Labels:
- cloudwatch
- s3
- export
LicenseUrl: LICENSE
Name: CloudWatch2S3-additional-account
ReadmeUrl: README.md
SemanticVersion: 1.0.0
SourceCodeUrl: https://github.com/CloudSnorkel/CloudWatch2S3
SpdxLicenseId: MIT
Parameters:
LogDestination:
AllowedPattern: arn:[a-z\-]+:logs:[a-z1-9\-]+:[0-9]+:destination:.*
Description: Log destination ARN from the outputs of the main template
Type: String
LogGroupNamePrefix:
Default: ''
Description: Prefix to match against log group that should be exported (leave
empty to export all log groups)
Type: String
SubscribeSchedule:
Default: rate(1 hour)
Description: Schedule to look for new log groups for export (in case CloudTrail
missed something)
Type: String
Resources:
LogSubscriberFunction:
Properties:
Code:
ZipFile:
Fn::Sub: |
import traceback
import boto3
import botocore.exceptions
import cfnresponse
logs_client = boto3.client("logs")
def subscribe(log_group_name):
print("Subscribe ", log_group_name)
if log_group_name.startswith("/aws/lambda/${AWS::StackName}") \
or log_group_name.startswith("/aws/kinesisfirehose/${AWS::StackName}"):
print("Skipping our log groups to avoid endless recursion")
return
try:
logs_client.put_subscription_filter(
logGroupName=log_group_name,
filterName="BucketBackupFilter",
filterPattern="",
destinationArn="${LogDestination}",
)
except logs_client.exceptions.LimitExceededException:
print(f"ERROR: Unable to subscribe to {log_group_name} as it already has an active subscription")
def matched_log_groups(prefix):
print(f"Finding all log groups with prefix '{prefix}'")
log_group_paginator = logs_client.get_paginator("describe_log_groups")
paginate_params = {}
if prefix:
paginate_params["logGroupNamePrefix"] = prefix
for log_group_page in log_group_paginator.paginate(**paginate_params):
for log_group in log_group_page["logGroups"]:
yield log_group["logGroupName"]
def subscribe_all():
for log_group_name in matched_log_groups("${LogGroupNamePrefix}"):
subscribe(log_group_name)
def unsubscribe_all():
for log_group_name in matched_log_groups(""):
print("Unsubscribe ", log_group_name)
try:
logs_client.delete_subscription_filter(
logGroupName=log_group_name,
filterName="BucketBackupFilter",
)
except botocore.exceptions.ClientError:
pass
def handler(event, context):
print('event:', event)
if "ResponseURL" in event and "RequestType" in event:
# custom resource callback
try:
if event["RequestType"] in ["Create", "Update"]:
print("Subscribe to all new log groups on resource", event["RequestType"])
subscribe_all()
elif event["RequestType"] == "Delete":
print("Unsubscribe all on resource", event["RequestType"])
unsubscribe_all()
cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, "ok")
except Exception as e:
try:
traceback.print_last()
except ValueError:
print("Caught exception but unable to print stack trace")
print(e)
cfnresponse.send(event, context, cfnresponse.FAILED, {}, "fail")
else:
# other call
detail_type = event.get("detail-type")
if detail_type == "AWS API Call via CloudTrail":
print("Subscribe to specific new log group from CloudTrail")
request_parameters = event['detail']['requestParameters']
if request_parameters:
log_group_name = request_parameters['logGroupName']
if log_group_name.startswith("${LogGroupNamePrefix}"):
subscribe(log_group_name)
else:
print(log_group_name, "doesn't match required prefix '${LogGroupNamePrefix}'")
else:
print("Bad parameters")
elif detail_type == "Scheduled Event":
print("Subscribe to all new log groups on schedule")
subscribe_all()
else:
print("Subscribe to all new log groups")
subscribe_all()
Handler: index.handler
Role:
Fn::GetAtt:
- LogSubscriberRole
- Arn
Runtime: python3.9
Timeout: 300
Type: AWS::Lambda::Function
LogSubscriberPermission:
Properties:
Action: lambda:InvokeFunction
FunctionName:
Fn::GetAtt:
- LogSubscriberFunction
- Arn
Principal:
Fn::Sub: events.${AWS::URLSuffix}
SourceArn:
Fn::GetAtt:
- LogSubscriberRule
- Arn
Type: AWS::Lambda::Permission
LogSubscriberRole:
Properties:
AssumeRolePolicyDocument:
Statement:
- Action:
- sts:AssumeRole
Effect: Allow
Principal:
Service:
- Fn::Sub: lambda.${AWS::URLSuffix}
Version: '2012-10-17'
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyDocument:
Statement:
- Action:
- logs:DeleteSubscriptionFilter
- logs:DescribeLogGroups
- logs:PutSubscriptionFilter
Effect: Allow
Resource: '*'
Sid: Logs
Version: '2012-10-17'
PolicyName: Logs
Type: AWS::IAM::Role
LogSubscriberRule:
Properties:
EventPattern:
detail:
eventName:
- CreateLogGroup
eventSource:
- Fn::Sub: logs.${AWS::URLSuffix}
detail-type:
- AWS API Call via CloudTrail
source:
- aws.logs
ScheduleExpression:
Ref: SubscribeSchedule
Targets:
- Arn:
Fn::GetAtt:
- LogSubscriberFunction
- Arn
Id: LogSubscriberLambda
Type: AWS::Events::Rule
Subscriber:
DependsOn:
- LogSubscriberFunction
Properties:
ServiceToken:
Fn::GetAtt:
- LogSubscriberFunction
- Arn
Type: Custom::Subscriber
Transform: AWS::Serverless-2016-10-31