forked from awsdocs/aws-doc-sdk-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroltower_wrapper.py
More file actions
476 lines (412 loc) · 18.3 KB
/
controltower_wrapper.py
File metadata and controls
476 lines (412 loc) · 18.3 KB
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import logging
import boto3
import time
from typing import Dict, List, Optional, Any
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
# snippet-start:[python.example_code.controltower.ControlTowerWrapper.class]
# snippet-start:[python.example_code.controltower.ControlTowerWrapper.decl]
class ControlTowerWrapper:
"""Encapsulates AWS Control Tower and Control Catalog functionality."""
def __init__(
self, controltower_client: boto3.client, controlcatalog_client: boto3.client
):
"""
:param controltower_client: A Boto3 Amazon ControlTower client.
:param controlcatalog_client: A Boto3 Amazon ControlCatalog client.
"""
self.controltower_client = controltower_client
self.controlcatalog_client = controlcatalog_client
@classmethod
def from_client(cls):
controltower_client = boto3.client("controltower")
controlcatalog_client = boto3.client("controlcatalog")
return cls(controltower_client, controlcatalog_client)
# snippet-end:[python.example_code.controltower.ControlTowerWrapper.decl]
# snippet-start:[python.example_code.controltower.ListBaselines]
def list_baselines(self):
"""
Lists all baselines.
:return: List of baselines.
:raises ClientError: If the listing operation fails.
"""
try:
paginator = self.controltower_client.get_paginator("list_baselines")
baselines = []
for page in paginator.paginate():
baselines.extend(page["baselines"])
return baselines
except ClientError as err:
if err.response["Error"]["Code"] == "AccessDeniedException":
logger.error(
"Access denied. Please ensure you have the necessary permissions."
)
else:
logger.error(
"Couldn't list baselines. Here's why: %s: %s",
err.response["Error"]["Code"],
err.response["Error"]["Message"],
)
raise
# snippet-end:[python.example_code.controltower.ListBaselines]
# snippet-start:[python.example_code.controltower.EnableBaseline]
def enable_baseline(
self,
target_identifier: str,
identity_center_baseline: str,
baseline_identifier: str,
baseline_version: str,
):
"""
Enables a baseline for the specified target if it's not already enabled.
:param target_identifier: The ARN of the target.
:param baseline_identifier: The identifier of baseline to enable.
:param identity_center_baseline: The identifier of identity center baseline if it is enabled.
:param baseline_version: The version of baseline to enable.
:return: The enabled baseline ARN or None if already enabled.
:raises ClientError: If enabling the baseline fails for reasons other than it being already enabled.
"""
try:
# Only include parameters if identity_center_baseline is not empty
parameters = []
if identity_center_baseline:
parameters = [
{
"key": "IdentityCenterEnabledBaselineArn",
"value": identity_center_baseline,
}
]
response = self.controltower_client.enable_baseline(
baselineIdentifier=baseline_identifier,
baselineVersion=baseline_version,
targetIdentifier=target_identifier,
parameters=parameters,
)
operation_id = response["operationIdentifier"]
while True:
status = self.get_baseline_operation(operation_id)
print(f"Baseline operation status: {status}")
if status in ["SUCCEEDED", "FAILED"]:
break
time.sleep(30)
return response["arn"]
except ClientError as err:
if err.response["Error"]["Code"] == "ValidationException":
if "already enabled" in err.response["Error"]["Message"]:
print("Baseline is already enabled for this target")
else:
print(
"Unable to enable baseline due to validation exception: %s: %s",
err.response["Error"]["Code"],
err.response["Error"]["Message"],
)
logger.error(
"Couldn't enable baseline. Here's why: %s: %s",
err.response["Error"]["Code"],
err.response["Error"]["Message"],
)
return None
# snippet-end:[python.example_code.controltower.EnableBaseline]
# snippet-start:[python.example_code.controltower.ListControls]
def list_controls(self):
"""
Lists all controls in the Control Tower control catalog.
:return: List of controls.
:raises ClientError: If the listing operation fails.
"""
try:
paginator = self.controlcatalog_client.get_paginator("list_controls")
controls = []
for page in paginator.paginate():
controls.extend(page["Controls"])
return controls
except ClientError as err:
if err.response["Error"]["Code"] == "AccessDeniedException":
logger.error(
"Access denied. Please ensure you have the necessary permissions."
)
else:
logger.error(
"Couldn't list controls. Here's why: %s: %s",
err.response["Error"]["Code"],
err.response["Error"]["Message"],
)
raise
# snippet-end:[python.example_code.controltower.ListControls]
# snippet-start:[python.example_code.controltower.EnableControl]
def enable_control(self, control_arn: str, target_identifier: str):
"""
Enables a control for a specified target.
:param control_arn: The ARN of the control to enable.
:param target_identifier: The identifier of the target (e.g., OU ARN).
:return: The operation ID.
:raises ClientError: If enabling the control fails.
"""
try:
print(control_arn)
print(target_identifier)
response = self.controltower_client.enable_control(
controlIdentifier=control_arn, targetIdentifier=target_identifier
)
operation_id = response["operationIdentifier"]
while True:
status = self.get_control_operation(operation_id)
print(f"Control operation status: {status}")
if status in ["SUCCEEDED", "FAILED"]:
break
time.sleep(30)
return operation_id
except ClientError as err:
if (
err.response["Error"]["Code"] == "ValidationException"
and "already enabled" in err.response["Error"]["Message"]
):
logger.info("Control is already enabled for this target")
return None
elif (
err.response["Error"]["Code"] == "ResourceNotFoundException"
and "not registered with AWS Control Tower"
in err.response["Error"]["Message"]
):
logger.error("Control Tower must be enabled to work with controls.")
return None
logger.error(
"Couldn't enable control. Here's why: %s: %s",
err.response["Error"]["Code"],
err.response["Error"]["Message"],
)
raise
# snippet-end:[python.example_code.controltower.EnableControl]
# snippet-start:[python.example_code.controltower.GetControlOperation]
def get_control_operation(self, operation_id: str):
"""
Gets the status of a control operation.
:param operation_id: The ID of the control operation.
:return: The operation status.
:raises ClientError: If getting the operation status fails.
"""
try:
response = self.controltower_client.get_control_operation(
operationIdentifier=operation_id
)
return response["controlOperation"]["status"]
except ClientError as err:
if err.response["Error"]["Code"] == "ResourceNotFoundException":
logger.error("Operation not found.")
else:
logger.error(
"Couldn't get control operation status. Here's why: %s: %s",
err.response["Error"]["Code"],
err.response["Error"]["Message"],
)
raise
# snippet-end:[python.example_code.controltower.GetControlOperation]
# snippet-start:[python.example_code.controltower.GetBaselineOperation]
def get_baseline_operation(self, operation_id: str):
"""
Gets the status of a baseline operation.
:param operation_id: The ID of the baseline operation.
:return: The operation status.
:raises ClientError: If getting the operation status fails.
"""
try:
response = self.controltower_client.get_baseline_operation(
operationIdentifier=operation_id
)
return response["baselineOperation"]["status"]
except ClientError as err:
if err.response["Error"]["Code"] == "ResourceNotFoundException":
logger.error("Operation not found.")
else:
logger.error(
"Couldn't get baseline operation status. Here's why: %s: %s",
err.response["Error"]["Code"],
err.response["Error"]["Message"],
)
raise
# snippet-end:[python.example_code.controltower.GetBaselineOperation]
# snippet-start:[python.example_code.controltower.DisableControl]
def disable_control(self, control_arn: str, target_identifier: str):
"""
Disables a control for a specified target.
:param control_arn: The ARN of the control to disable.
:param target_identifier: The identifier of the target (e.g., OU ARN).
:return: The operation ID.
:raises ClientError: If disabling the control fails.
"""
try:
response = self.controltower_client.disable_control(
controlIdentifier=control_arn, targetIdentifier=target_identifier
)
operation_id = response["operationIdentifier"]
while True:
status = self.get_control_operation(operation_id)
print(f"Control operation status: {status}")
if status in ["SUCCEEDED", "FAILED"]:
break
time.sleep(30)
return operation_id
except ClientError as err:
if err.response["Error"]["Code"] == "ResourceNotFoundException":
logger.error("Control not found.")
else:
logger.error(
"Couldn't disable control. Here's why: %s: %s",
err.response["Error"]["Code"],
err.response["Error"]["Message"],
)
raise
# snippet-end:[python.example_code.controltower.DisableControl]
# snippet-start:[python.example_code.controltower.ListLandingZones]
def list_landing_zones(self):
"""
Lists all landing zones.
:return: List of landing zones.
:raises ClientError: If the listing operation fails.
"""
try:
paginator = self.controltower_client.get_paginator("list_landing_zones")
landing_zones = []
for page in paginator.paginate():
landing_zones.extend(page["landingZones"])
return landing_zones
except ClientError as err:
if err.response["Error"]["Code"] == "AccessDeniedException":
logger.error(
"Access denied. Please ensure you have the necessary permissions."
)
else:
logger.error(
"Couldn't list landing zones. Here's why: %s: %s",
err.response["Error"]["Code"],
err.response["Error"]["Message"],
)
raise
# snippet-end:[python.example_code.controltower.ListLandingZones]
# snippet-start:[python.example_code.controltower.ListEnabledBaselines]
def list_enabled_baselines(self):
"""
Lists all enabled baselines.
:return: List of enabled baselines.
:raises ClientError: If the listing operation fails.
"""
try:
paginator = self.controltower_client.get_paginator("list_enabled_baselines")
enabled_baselines = []
for page in paginator.paginate():
enabled_baselines.extend(page["enabledBaselines"])
return enabled_baselines
except ClientError as err:
if err.response["Error"]["Code"] == "ResourceNotFoundException":
logger.error("Target not found.")
else:
logger.error(
"Couldn't list enabled baselines. Here's why: %s: %s",
err.response["Error"]["Code"],
err.response["Error"]["Message"],
)
raise
# snippet-end:[python.example_code.controltower.ListEnabledBaselines]
# snippet-start:[python.example_code.controltower.ResetEnabledBaseline]
def reset_enabled_baseline(self, enabled_baseline_identifier: str):
"""
Resets an enabled baseline for a specific target.
:param enabled_baseline_identifier: The identifier of the enabled baseline to reset.
:return: The operation ID.
:raises ClientError: If resetting the baseline fails.
"""
try:
response = self.controltower_client.reset_enabled_baseline(
enabledBaselineIdentifier=enabled_baseline_identifier
)
operation_id = response["operationIdentifier"]
while True:
status = self.get_baseline_operation(operation_id)
print(f"Baseline operation status: {status}")
if status in ["SUCCEEDED", "FAILED"]:
break
time.sleep(30)
return operation_id
except ClientError as err:
if err.response["Error"]["Code"] == "ResourceNotFoundException":
logger.error("Target not found.")
else:
logger.error(
"Couldn't reset enabled baseline. Here's why: %s: %s",
err.response["Error"]["Code"],
err.response["Error"]["Message"],
)
raise
# snippet-end:[python.example_code.controltower.ResetEnabledBaseline]
# snippet-start:[python.example_code.controltower.DisableBaseline]
def disable_baseline(self, enabled_baseline_identifier: str):
"""
Disables a baseline for a specific target and waits for the operation to complete.
:param enabled_baseline_identifier: The identifier of the baseline to disable.
:return: The operation ID.
:raises ClientError: If disabling the baseline fails.
"""
try:
response = self.controltower_client.disable_baseline(
enabledBaselineIdentifier=enabled_baseline_identifier
)
operation_id = response["operationIdentifier"]
while True:
status = self.get_baseline_operation(operation_id)
print(f"Baseline operation status: {status}")
if status in ["SUCCEEDED", "FAILED"]:
break
time.sleep(30)
return response["operationIdentifier"]
except ClientError as err:
if err.response["Error"]["Code"] == "ConflictException":
print(
f"Conflict disabling baseline: {err.response['Error']['Message']}. Skipping disable step."
)
return None
else:
logger.error(
"Couldn't disable baseline. Here's why: %s: %s",
err.response["Error"]["Code"],
err.response["Error"]["Message"],
)
raise
# snippet-end:[python.example_code.controltower.DisableBaseline]
# snippet-start:[python.example_code.controltower.ListEnabledControls]
def list_enabled_controls(self, target_identifier: str):
"""
Lists all enabled controls for a specific target.
:param target_identifier: The identifier of the target (e.g., OU ARN).
:return: List of enabled controls.
:raises ClientError: If the listing operation fails.
"""
enabled_controls = []
try:
paginator = self.controltower_client.get_paginator("list_enabled_controls")
for page in paginator.paginate(targetIdentifier=target_identifier):
enabled_controls.extend(page["enabledControls"])
return enabled_controls
except ClientError as err:
if err.response["Error"]["Code"] == "AccessDeniedException":
logger.error(
"Access denied. Please ensure you have the necessary permissions."
)
return enabled_controls
elif (
err.response["Error"]["Code"] == "ResourceNotFoundException"
and "not registered with AWS Control Tower"
in err.response["Error"]["Message"]
):
logger.error("Control Tower must be enabled to work with controls.")
return enabled_controls
else:
logger.error(
"Couldn't list enabled controls. Here's why: %s: %s",
err.response["Error"]["Code"],
err.response["Error"]["Message"],
)
raise
# snippet-end:[python.example_code.controltower.ListEnabledControls]
# snippet-end:[python.example_code.controltower.ControlTowerWrapper.class]