-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathct_configrecorder_override_consumer.py
141 lines (116 loc) · 5.96 KB
/
ct_configrecorder_override_consumer.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
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
#
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify,merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
import boto3
import json
import logging
import botocore.exceptions
import os
def lambda_handler(event, context):
LOG_LEVEL = os.getenv('LOG_LEVEL')
logging.getLogger().setLevel(LOG_LEVEL)
try:
logging.info('Event Body:')
body = json.loads(event['Records'][0]['body'])
account_id = body['Account']
aws_region = body['Region']
event = body['Event']
logging.info(f'Extracted Account: {account_id}')
logging.info(f'Extracted Region: {aws_region}')
logging.info(f'Extracted Event: {event}')
bc = botocore.__version__
b3 = boto3.__version__
logging.info(f'Botocore : {bc}')
logging.info(f'Boto3 : {b3}')
STS = boto3.client("sts")
def assume_role(account_id, role='AWSControlTowerExecution'):
'''
Return a session in the target account using Control Tower Role
'''
try:
curr_account = STS.get_caller_identity()['Account']
if curr_account != account_id:
part = STS.get_caller_identity()['Arn'].split(":")[1]
role_arn = 'arn:' + part + ':iam::' + account_id + ':role/' + role
ses_name = str(account_id + '-' + role)
response = STS.assume_role(RoleArn=role_arn, RoleSessionName=ses_name)
sts_session = boto3.Session(
aws_access_key_id=response['Credentials']['AccessKeyId'],
aws_secret_access_key=response['Credentials']['SecretAccessKey'],
aws_session_token=response['Credentials']['SessionToken'])
return sts_session
except botocore.exceptions.ClientError as exe:
logging.error('Unable to assume role')
raise exe
sts_session = assume_role(account_id)
logging.info(f'Printing STS session: {sts_session}')
# Use the session and create a client for configservice
configservice = sts_session.client('config', region_name=aws_region)
# Describe configuration recorder
configrecorder = configservice.describe_configuration_recorders()
logging.info(f'Existing Configuration Recorder :', configrecorder)
# ControlTower created configuration recorder with name "aws-controltower-BaselineConfigRecorder" and we will update just that
try:
role_arn = 'arn:aws:iam::' + account_id + ':role/aws-controltower-ConfigRecorderRole'
CONFIG_RECORDER_EXCLUSION_RESOURCE_STRING = os.getenv('CONFIG_RECORDER_EXCLUDED_RESOURCE_LIST')
CONFIG_RECORDER_EXCLUSION_RESOURCE_LIST = CONFIG_RECORDER_EXCLUSION_RESOURCE_STRING.split(',')
# Event = Delete is when stack is deleted, we rollback changed made and leave it as ControlTower Intended
if event == 'Delete':
response = configservice.put_configuration_recorder(
ConfigurationRecorder={
'name': 'aws-controltower-BaselineConfigRecorder',
'roleARN': role_arn,
'recordingGroup': {
'allSupported': True,
'includeGlobalResourceTypes': False
}
})
logging.info(f'Response for put_configuration_recorder :{response} ')
else:
response = configservice.put_configuration_recorder(
ConfigurationRecorder={
'name': 'aws-controltower-BaselineConfigRecorder',
'roleARN': role_arn,
'recordingGroup': {
'allSupported': False,
'includeGlobalResourceTypes': False,
'exclusionByResourceTypes': {
'resourceTypes': CONFIG_RECORDER_EXCLUSION_RESOURCE_LIST
},
'recordingStrategy': {
'useOnly': 'EXCLUSION_BY_RESOURCE_TYPES'
}
}
})
logging.info(f'Response for put_configuration_recorder :{response} ')
# lets describe for configuration recorder after the update
configrecorder = configservice.describe_configuration_recorders()
logging.info(f'Post Change Configuration recorder : {configrecorder}')
except botocore.exceptions.ClientError as exe:
logging.error('Unable to Update Config Recorder for Account and Region : ', account_id, aws_region)
configrecorder = configservice.describe_configuration_recorders()
logging.info(f'Exception : {configrecorder}')
raise exe
return {
'statusCode': 200
}
except Exception as e:
exception_type = e.__class__.__name__
exception_message = str(e)
logging.exception(f'{exception_type}: {exception_message}')