-
Notifications
You must be signed in to change notification settings - Fork 1
/
CFN-Drift-Reports.yaml
396 lines (354 loc) · 13.4 KB
/
CFN-Drift-Reports.yaml
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
---
AWSTemplateFormatVersion: '2010-09-09'
Description: >-
This stack will create a Lambda Function which then monitor all other CFN
stack in the given account.
Metadata:
Author: Nordcloud (Tamas Kiss)
Project: CFN Drift Monitoring
Parameters:
CronLine1:
Description: To define the times when the Drift detection is running
Type: String
Default: "0 6,19 * * ? *"
CronLine2:
Description: To define the times when the Drift Search is running
Type: String
Default: "10 6,19 * * ? *"
EmailAddress:
Description: |
The e-mail adress where drift notification should be sent, leave empty to disable
Type: String
Default: ""
Conditions:
SendEmail:
!Not [!Equals [!Ref EmailAddress, ""]]
Resources:
CFNLambdaExecutionRole:
Type: 'AWS::IAM::Role'
Properties:
ManagedPolicyArns:
- arn:aws:iam::aws:policy/ReadOnlyAccess
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: /
Policies:
- PolicyName: AllowLogs
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: 'arn:aws:logs:*:*:*'
- PolicyName: AllowCFN
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- 'cloudformation:*' # TODO no fine grade IAM permission for drift yet
Resource: '*'
- PolicyName: AllowSNS
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- sns:ListSubscriptions
- sns:ListSubscriptionsByTopic
- sns:ListTopics
- sns:Publish
Resource: !Ref NotificationSNSTopic
LambdaLambdaExecutionRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: /
Policies:
- PolicyName: AllowLogs
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: 'arn:aws:logs:*:*:*'
- PolicyName: AllowLambda
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- lambda:AddLayerVersionPermission
- lambda:GetLayerVersion
- lambda:GetLayerVersionPolicy
- lambda:ListLayerVersions
- lambda:PublishLayerVersion
Resource: '*'
LambdaLayerBuilderFuntion:
Type: 'AWS::Lambda::Function'
Properties:
Description: 'Build a lambda layer with the latest version of boto3'
Code:
ZipFile: |
"""
Lambda function to create a Lambda layer from CFN
"""
from __future__ import print_function
import subprocess
import sys
import os
import zipfile
import json
import importlib
try:
import cfnresponse
CFN_CALL = True
except ImportError:
CFN_CALL = False
PKG_DIR = "/tmp/packages/python/lib/python3.7/site-packages"
PKG_ROOT = "/tmp/packages"
def lambda_handler(event, context):
"""
Main function to be called by Lambda
"""
request_type = event['RequestType']
packages = event['ResourceProperties']['requirements']
name = event['ResourceProperties']['Name']
region = event['ResourceProperties']['Region']
if request_type == 'Create' or request_type == 'Update':
pass
else:
print("Nothing to do here")
# Tell CFN that do are done doing nothing
if CFN_CALL:
cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, '')
# Exit at this point
sys.exit
install_with_pip(packages)
zipit(PKG_ROOT, "/tmp/layer")
layer_arn = publish_layer(name, region)
if CFN_CALL:
data = { "Arn": layer_arn}
physical_id = layer_arn
cfnresponse.send(event, context, cfnresponse.SUCCESS, data, physical_id)
def zipit(src, dst):
"""
Create a zip file from src into dst.zip
"""
zipf = zipfile.ZipFile("%s.zip" % (dst), "w", zipfile.ZIP_DEFLATED)
abs_src = os.path.abspath(src)
for dirname, _, files in os.walk(src):
for filename in files:
absname = os.path.abspath(os.path.join(dirname, filename))
arcname = absname[len(abs_src) + 1:]
zipf.write(absname, arcname)
zipf.close()
def install_with_pip(packages):
"""
Install pip package into /tmp folder
"""
print(" -- Installing pip packages")
logfile = open("/tmp/pip-install.log", "wb")
for package in packages:
print(" ---- Installing {}".format(package))
subprocess.check_call([
sys.executable, '-m', 'pip', 'install',
'--upgrade', '--no-deps', '-t', PKG_DIR, package], stdout=logfile)
def publish_layer(name, region):
"""
Publish the built zip as a Lambda layer
"""
logfile = open("/tmp/pip-install.log", "wb")
subprocess.check_call([
sys.executable, '-m', 'pip', 'install',
'--upgrade', '-t', '/tmp/upload', 'boto3'], stdout=logfile)
# my pip location
sys.path.insert(0, '/tmp/upload')
import botocore
importlib.reload(botocore)
import boto3
client = boto3.client('lambda', region_name=region)
response = client.publish_layer_version(
LayerName=name,
Description='Build with CFN Custom Resource',
Content={'ZipFile': file_get_content('/tmp/layer.zip')},
CompatibleRuntimes=['python3.7'])
return response['LayerVersionArn']
def file_get_content(filename):
"""
Read the ZIP into python parsable var
"""
with open(filename, 'rb') as filevar:
return filevar.read()
Handler: index.lambda_handler
Runtime: python3.7
Timeout: 300
Role: !GetAtt LambdaLambdaExecutionRole.Arn
TriggerDriftDetectFunction:
Type: 'AWS::Lambda::Function'
Properties:
Description: 'Reqest drift detection to run against all CFN template'
Code:
ZipFile: |
"""
CFN Drift tool, detect, scan, then alarm
"""
from __future__ import print_function
import boto3
from botocore.exceptions import ClientError
REGIONS = boto3.session.Session().get_available_regions('cloudformation')
def lambda_handler(event, context):
"""
This function routes to different parts of the script
"""
if event['EventType'] == 'detect':
detect()
elif event['EventType'] == 'find':
find(event)
def detect():
"""
This function reqest AWS to run the drift detection
in all stack in all region
"""
for region in REGIONS:
sts = boto3.client('sts', region_name=region)
try:
me = sts.get_caller_identity()
print("Checking {} region".format(region))
cfn = boto3.client('cloudformation', region_name=region)
cfn_list = cfn.describe_stacks()
for stack in cfn_list['Stacks']:
print(" -- Found stack: {}".format(stack['StackName']))
call = cfn.detect_stack_drift(StackName=stack['StackName'])
print(call)
except ClientError as exc:
if exc.response['Error']['Code'] == 'InvalidClientTokenId':
print("This IAM role is not autharized to use {} region.".format(region))
else:
print("Unexpected error: {}".format(exc))
def find(event):
"""
After the detect run on all, this function check the statuses
"""
drifted = []
sns = boto3.client('sns')
for region in REGIONS:
sts = boto3.client('sts', region_name=region)
try:
me = sts.get_caller_identity()
print("Searching for stacks in {} region".format(region))
cfn = boto3.client('cloudformation', region_name=region)
cfn_list = cfn.describe_stacks()
for stack in cfn_list['Stacks']:
print(" Found stack: {}".format(stack['StackName']))
response = cfn.describe_stack_resource_drifts(
StackName=stack['StackName']
)
for resource in response['StackResourceDrifts']:
if resource['StackResourceDriftStatus'] != "IN_SYNC":
drifted.append(resource)
except ClientError as exc:
if exc.response['Error']['Code'] == 'InvalidClientTokenId':
print("This IAM role is not autharized to use {} region.".format(region))
else:
print("Unexpected error: {}".format(exc))
message = ""
for resource in drifted:
message += str("*{}* status found on *{}* stack in the *{}* resource\n".format(
resource['StackResourceDriftStatus'],
resource['StackId'],
resource['LogicalResourceId']))
message += str("this is a *{}* type resource, with the ID *{}*\n\n".format(
resource['ResourceType'],
resource['PhysicalResourceId']))
response = sns.publish(
TopicArn=event['TopicArn'],
Message=message,
Subject='Drift Detected')
Handler: index.lambda_handler
Runtime: python3.7
Timeout: 180
Role: !GetAtt CFNLambdaExecutionRole.Arn
Layers:
- !GetAtt Boto3LambdaLayer.Arn
Boto3LambdaLayer:
Properties:
ServiceToken: !GetAtt LambdaLayerBuilderFuntion.Arn
Name: boto3-latest
Region: !Ref "AWS::Region"
requirements:
- boto3
- botocore
Type: Custom::LayerBuilder
DetectSchedule:
Type: 'AWS::Events::Rule'
Properties:
Description: 'This is the CFN Drift monitoring tool [Detect]'
ScheduleExpression: !Sub "cron(${CronLine1})"
State: ENABLED
Targets:
- Arn: !GetAtt TriggerDriftDetectFunction.Arn
Id: TriggerDriftDetectFunctionV1
Input: !Sub |
{"EventType": "detect", "TopicArn": "${NotificationSNSTopic}" }
FindSchedule:
Type: 'AWS::Events::Rule'
Properties:
Description: 'This is the CFN Drift monitoring tool [Find]'
ScheduleExpression: !Sub "cron(${CronLine2})"
State: ENABLED
Targets:
- Arn: !GetAtt TriggerDriftDetectFunction.Arn
Id: TriggerDriftDetectFunctionV2
Input: !Sub |
{"EventType": "find", "TopicArn": "${NotificationSNSTopic}" }
DectectEventLambdaPermission:
Type: 'AWS::Lambda::Permission'
Properties:
FunctionName: !Ref TriggerDriftDetectFunction
Action: 'lambda:InvokeFunction'
Principal: events.amazonaws.com
SourceArn: !GetAtt DetectSchedule.Arn
FindEventLambdaPermission:
Type: 'AWS::Lambda::Permission'
Properties:
FunctionName: !Ref TriggerDriftDetectFunction
Action: 'lambda:InvokeFunction'
Principal: events.amazonaws.com
SourceArn: !GetAtt FindSchedule.Arn
NotificationSNSTopic:
Type: 'AWS::SNS::Topic'
Properties:
DisplayName: CFN-DRIFT
EmailNotification:
Condition: SendEmail
Type: "AWS::SNS::Subscription"
Properties:
Endpoint: !Ref EmailAddress
Protocol: email
TopicArn: !Ref NotificationSNSTopic
Outputs:
NotificationSNSTopic:
Description: SNS topic where Drift notifucations are sent
Value: !Ref NotificationSNSTopic