-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeploy.py
More file actions
executable file
·1209 lines (952 loc) · 47.9 KB
/
deploy.py
File metadata and controls
executable file
·1209 lines (952 loc) · 47.9 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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
OpenSecOps Foundation Component Deployment Script
This script provides unified deployment orchestration for OpenSecOps Foundation components,
supporting multiple deployment patterns (SAM, CloudFormation, Scripts) with sophisticated
parameter resolution and cross-account operations.
Key Features:
- Parameter resolution with cross-references ({parameter-name} syntax)
- Computed parameters like {all-regions} from main-region + other-regions
- Cross-account role assumption for organization-wide deployments
- Support for SAM serverless applications, CloudFormation infrastructure, and custom scripts
- Dry-run mode for safe testing and validation
- Verbose logging for debugging and monitoring
Usage:
./deploy [--dry-run] [--verbose]
This script is distributed to all Foundation components via the refresh mechanism to ensure
consistent deployment behavior across the OpenSecOps ecosystem.
For detailed architecture information, see: Installer/ARCHITECTURE.md
"""
import os
import sys
import subprocess
import toml
import json
import boto3
import re
import botocore
from botocore.exceptions import ClientError
from botocore.exceptions import WaiterError
import time
import shutil
import argparse
# Create an STS client
STS_CLIENT = boto3.client('sts')
# ---------------------------------------------------------------------------------------
#
# Common
#
# ---------------------------------------------------------------------------------------
# Define colors
YELLOW = "\033[93m"
LIGHT_BLUE = "\033[94m"
GREEN = "\033[92m"
RED = "\033[91m"
GRAY = "\033[90m"
END = "\033[0m"
BOLD = "\033[1m"
def printc(color, string, **kwargs):
print(f"{color}{string}\033[K{END}", **kwargs)
def check_aws_sso_session():
try:
# Try to get the user's identity
subprocess.run(['aws', 'sts', 'get-caller-identity'], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except subprocess.CalledProcessError:
# If the command failed, the user is not logged in
printc(RED, "You do not have a valid AWS SSO session. Please run 'aws sso login' and try again.")
return False
# If the command succeeded, the user is logged in
return True
def load_toml(toml_file):
# Load the TOML file
try:
config = toml.load(toml_file)
except Exception as e:
printc(RED, f"Error loading {toml_file}: {str(e)}")
return None
return config
def get_account_data_from_toml(account_key, id_or_profile):
toml_file = '../Installer/apps/accounts.toml'
# Load the TOML file
config = load_toml(toml_file)
# Get the AWS SSO profile or id
try:
data = config[account_key][id_or_profile]
except KeyError:
printc(RED, f"Error: '{account_key}' account not found in {toml_file}")
return None
return data
def get_all_parameters(opensecops_app):
toml_file = f'../Installer/apps/{opensecops_app}/parameters.toml'
# Load and return the whole TOML file
config = load_toml(toml_file)
return config
def parameters_to_sam_string(params, repo_name):
section = params[repo_name]['SAM']
params_list = []
for k, v in section.items():
v = dereference(v, params)
params_list.append(f'{k}="{v}"')
return ' '.join(params_list)
def parameters_to_cloudformation_json(params, repo_name, template_name):
section = params[repo_name][template_name]
cf_params = []
for k, v in section.items():
v = dereference(v, params)
cf_params.append({
'ParameterKey': k,
'ParameterValue': v
})
return cf_params
def script_parameters_to_dictionary(script_name, params, repo_name):
section = params[repo_name][script_name]
result = {}
for k, v in section.items():
v = dereference(v, params)
result[k] = v
return result
def dereference(value, params):
# If not a string, just return
if not isinstance(value, str):
return value
# Check if value is exactly '{all-regions}'
if value == '{all-regions}':
# Get main region and other regions
main_region = params.get('main-region', '')
other_regions = params.get('other-regions', [])
# Handle case where other-regions is a comma-separated string (from script context)
if isinstance(other_regions, str):
other_regions = [r.strip() for r in other_regions.split(',') if r.strip()]
# Add main region as a new first element
all_regions = [main_region] + other_regions
# Return a list of strings
return all_regions
# Check if value contains a reference
elif "{" in value and "}" in value:
def substitute(m):
param = m.group(1)
if param in params:
result = params[param]
# Convert lists to comma-separated strings for script arguments
if isinstance(result, list):
return ','.join(result)
return result
else:
# If not found in params, try to get account data from TOML
account_data = get_account_data_from_toml(param, 'id')
if account_data is not None:
return account_data
else:
raise ValueError(f"Parameter {param} not found")
# Replace any string enclosed in braces with the corresponding parameter
value = re.sub(r'\{(.+?)\}', substitute, value)
return value
# ---------------------------------------------------------------------------------------
#
# SAM
#
# ---------------------------------------------------------------------------------------
def process_sam(sam, repo_name, params, dry_run, verbose):
printc(LIGHT_BLUE, "")
printc(LIGHT_BLUE, "")
printc(LIGHT_BLUE, "================================================")
printc(LIGHT_BLUE, "")
printc(LIGHT_BLUE, f" {repo_name} (SAM)")
printc(LIGHT_BLUE, "")
printc(LIGHT_BLUE, "------------------------------------------------")
printc(LIGHT_BLUE, "")
sam_account = sam['profile']
sam_regions = dereference(sam['regions'], params)
if isinstance(sam_regions, str):
sam_regions = [sam_regions]
stack_name = sam['stack-name']
capabilities = sam.get('capabilities', 'CAPABILITY_IAM')
s3_prefix = sam.get('s3-prefix', stack_name)
tags = 'infra:immutable="true"'
# Get the AWS SSO profile
sam_profile = get_account_data_from_toml(sam_account, 'profile')
# Get the SAM parameter overrides
sam_parameter_overrides = parameters_to_sam_string(params, repo_name)
try:
printc(LIGHT_BLUE, "Executing 'git pull'...")
subprocess.run(['git', 'pull'], check=True)
printc(LIGHT_BLUE, "")
printc(LIGHT_BLUE, "Executing 'sam build'...")
args = ['sam', 'build', '--parallel', '--cached']
try:
if verbose:
subprocess.run(args, check=True)
else:
subprocess.run(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
except subprocess.CalledProcessError:
printc(RED, "An error occurred. Retrying after cleaning build directory...")
# Remove the .aws-sam directory
shutil.rmtree('.aws-sam', ignore_errors=True)
# Retry the build command, always verbosely
subprocess.run(args, check=True)
for region in sam_regions:
printc(LIGHT_BLUE, "")
printc(LIGHT_BLUE, "")
printc(LIGHT_BLUE, "------------------------------------------------")
printc(LIGHT_BLUE, "")
printc(LIGHT_BLUE, f" Deploying {stack_name} to {region}...")
printc(LIGHT_BLUE, "")
printc(LIGHT_BLUE, "------------------------------------------------")
printc(LIGHT_BLUE, "")
args = [
'sam', 'deploy',
'--stack-name', stack_name,
'--capabilities', capabilities,
'--resolve-s3',
'--region', region,
'--profile', sam_profile,
'--parameter-overrides', sam_parameter_overrides,
'--s3-prefix', s3_prefix,
'--tags', tags,
'--no-confirm-changeset',
'--no-disable-rollback',
'--no-fail-on-empty-changeset',
]
if dry_run:
args.append('--no-execute-changeset')
printc(GREEN, "Executing 'sam deploy' with --no-execute-changeset...")
else:
printc(LIGHT_BLUE, "Executing 'sam deploy'...")
if verbose:
args.append('--debug')
subprocess.run(args, check=True)
printc(GREEN, "")
printc(GREEN + BOLD, "Deployment completed successfully.")
except subprocess.CalledProcessError as e:
printc(RED, f"An error occurred while executing the command: {str(e)}")
printc(GREEN, "")
# ---------------------------------------------------------------------------------------
#
# Scripts
#
# ---------------------------------------------------------------------------------------
def process_scripts(scripts, repo_name, params, dry_run, verbose):
printc(LIGHT_BLUE, "")
printc(LIGHT_BLUE, "")
printc(LIGHT_BLUE, "=================================================")
printc(LIGHT_BLUE, "")
printc(LIGHT_BLUE, f" {repo_name} (Scripts)")
printc(LIGHT_BLUE, "")
printc(LIGHT_BLUE, "-------------------------------------------------")
printc(LIGHT_BLUE, "")
for script in scripts:
regions = script.get('regions', '{main-region}')
regions = dereference(regions, params)
if isinstance(regions, str):
regions = [regions]
account_str = script.get('account', '{admin-account}')
account_id = dereference(account_str, params)
if verbose:
printc(GRAY, f"account_id: {account_id}")
profile = script.get('profile', 'admin-account')
profile = get_account_data_from_toml(profile, 'profile')
if verbose:
printc(GRAY, f"profile: {profile}")
if verbose:
printc(GRAY, f"script: {script}")
name = script['name']
our_params = script_parameters_to_dictionary(name, params, repo_name)
if verbose:
printc(GRAY, f"our_params: {our_params}")
cmd = ['./' + name]
if dry_run:
cmd.append('--dry-run')
if verbose:
cmd.append('--verbose')
for k, v in script.get('args', []):
cmd.append(k)
if isinstance(v, str) and v.endswith('.toml'):
try:
# Read the TOML file
with open(v, 'r') as toml_file:
toml_data = toml.load(toml_file)
# Convert the TOML data to JSON
json_string = json.dumps(toml_data)
except FileNotFoundError:
print(f"The file {v} does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
cmd.append(json_string)
else:
# Check if this parameter was already resolved in our_params
param_key = v.strip('{}') if v.startswith('{') and v.endswith('}') else None
if param_key and param_key in our_params:
# Use the already-resolved value from our_params
result = our_params[param_key]
if isinstance(result, list):
cmd.append(','.join(result)) # Convert list to comma-separated string
else:
cmd.append(result)
else:
# Fall back to dereference for unresolved parameters
result = dereference(v, our_params)
if isinstance(result, list):
cmd.append(','.join(result)) # Convert list to comma-separated string
else:
cmd.append(result)
if verbose:
printc(GRAY, '')
printc(GRAY, f"cmd: {cmd}")
for region in regions:
printc(LIGHT_BLUE, "")
printc(LIGHT_BLUE, "")
printc(LIGHT_BLUE, "------------------------------------------------")
printc(LIGHT_BLUE, "")
printc(LIGHT_BLUE, f" Running script ./{name} in {region}...")
printc(LIGHT_BLUE, "")
printc(LIGHT_BLUE, "------------------------------------------------")
printc(LIGHT_BLUE, "")
try:
subprocess.run(cmd, check=True)
except subprocess.CalledProcessError as e:
print(f"Command '{e.cmd}' returned non-zero exit status {e.returncode}.")
# ---------------------------------------------------------------------------------------
#
# CloudFormation
#
# ---------------------------------------------------------------------------------------
# Function to get a client for the specified service, account, and region
def get_client(client_type, account_id, region, role):
# Assume the specified role in the specified account
other_session = STS_CLIENT.assume_role(
RoleArn=f"arn:aws:iam::{account_id}:role/{role}",
RoleSessionName=f"deploy_cloudformation_{account_id}"
)
access_key = other_session['Credentials']['AccessKeyId']
secret_key = other_session['Credentials']['SecretAccessKey']
session_token = other_session['Credentials']['SessionToken']
# Create a client using the assumed role credentials and specified region
return boto3.client(
client_type,
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
aws_session_token=session_token,
region_name=region
)
def does_stack_exist(stack_name, account_id, region, role):
try:
# Get CloudFormation client for the specified account and region
cf_client = get_client("cloudformation", account_id, region, role)
# Describe the stack using the provided name
cf_client.describe_stacks(StackName=stack_name)
# If no exception is raised, the stack exists
return True
except ClientError as e:
error_code = e.response['Error']['Code']
if error_code == 'ValidationError' and 'does not exist' in e.response['Error']['Message']:
return False
else:
raise e
def does_stackset_exist(stackset_name, account_id, region, role):
try:
# Get CloudFormation client for the specified account and region
cf_client = get_client("cloudformation", account_id, region, role)
# Describe the stack set using the provided name
cf_client.describe_stack_set(StackSetName=stackset_name)
# If no exception is raised, the stack set exists
return True
except ClientError as e:
error_code = e.response['Error']['Code']
if error_code == 'StackSetNotFoundException':
return False
else:
raise e
def read_cloudformation_template(path):
"""
Reads the CloudFormation template from the specified path and checks for size constraints.
Parameters:
- path (str): Path to the CloudFormation template file.
Returns:
- template (str): Contents of the CloudFormation template file.
Raises:
- Exception if the file is missing or exceeds the size limit.
"""
try:
# Read the file content
with open(path, 'r') as file:
template = file.read()
# Check for size constraints
if len(template.encode('utf-8')) > 51200: # CloudFormation string template size limit is 51,200 bytes
raise Exception("The CloudFormation template exceeds the maximum size limit of 51,200 bytes.")
return template
except FileNotFoundError:
raise Exception(f"The specified CloudFormation template at path '{path}' was not found.")
def process_stack(action, resource_type, name, template_body, parameters, capabilities, account_id, region, role, dry_run, verbose, **kwargs):
op = 'Creating' if action == 'create' else 'Updating'
dry_run_str = 'Dry run: NOT ' if dry_run else ''
printc(YELLOW, f"{dry_run_str}{op} {resource_type} {name} in AWS account {account_id} in region {region}...")
cf_client = get_client('cloudformation', account_id, region, role)
tags = [{'Key': 'infra:immutable', 'Value': 'true'}]
try:
if resource_type == 'stack':
# Create a change set
change_set_name = 'ChangeSet-' + str(int(time.time()))
if action == 'create':
resources = parse_template(template_body)
print_template_resources(resources)
if dry_run:
return False
printc(YELLOW, "Creating the stack...")
response = cf_client.create_stack(
StackName=name,
TemplateBody=template_body,
Parameters=parameters,
Capabilities=[capabilities],
Tags=tags
)
elif action == 'update':
response = cf_client.create_change_set(
StackName=name,
TemplateBody=template_body,
Parameters=parameters,
Capabilities=[capabilities],
Tags=tags,
ChangeSetName=change_set_name,
)
response = cf_client.describe_change_set(
StackName=name,
ChangeSetName=change_set_name,
)
if response['Status'] == 'FAILED' and "The submitted information didn't contain changes." in response['StatusReason']:
printc(GREEN, f"No changes.")
return False
else:
# Wait for the change set to be created
try:
printc(LIGHT_BLUE, "Waiting for changeset to be created...")
waiter = cf_client.get_waiter('change_set_create_complete')
waiter.wait(
StackName=name,
ChangeSetName=change_set_name,
)
except WaiterError as we:
# Check if the last_response attribute exists and contains the necessary information
if hasattr(we, 'last_response') and 'Status' in we.last_response and 'StatusReason' in we.last_response:
status = we.last_response['Status']
status_reason = we.last_response['StatusReason']
if status == 'FAILED' and "The submitted information didn't contain changes." in status_reason:
printc(GREEN, f"No changes.")
return False
else:
# If the expected details are not available, re-raise the exception
raise
# Display the changes
response = cf_client.describe_change_set(
StackName=name,
ChangeSetName=change_set_name,
)
print_change_set(response)
if dry_run:
return False
# Execute the change set
printc(YELLOW, "Executing the changeset...")
return cf_client.execute_change_set(
StackName=name,
ChangeSetName=change_set_name,
)
elif resource_type == 'stackset':
if dry_run:
return False
if action == 'create':
return cf_client.create_stack_set(StackSetName=name, TemplateBody=template_body, Parameters=parameters, Capabilities=[capabilities], Tags=tags, **kwargs)
elif action == 'update':
return cf_client.update_stack_set(StackSetName=name, TemplateBody=template_body, Parameters=parameters, Capabilities=[capabilities], Tags=tags, **kwargs)
return True
except botocore.exceptions.ClientError as e:
if "No updates are to be performed" in str(e):
printc(GREEN, f"{resource_type.capitalize()} {action}: No changes are needed.")
return False
else:
raise e
def print_change_set(change_set):
if change_set['Status'] == 'FAILED' and "The submitted information didn't contain changes." in change_set['StatusReason']:
printc(GREEN, "None.")
elif 'Changes' in change_set and change_set['Changes']:
# Calculate the maximum length of each column
max_resource_len = max(len(change['ResourceChange']['ResourceType']) for change in change_set['Changes'])
max_action_len = max(len(change['ResourceChange']['Action']) for change in change_set['Changes'])
max_id_len = max(len(change['ResourceChange']['LogicalResourceId']) for change in change_set['Changes'])
dash_len = max_resource_len + max_action_len + max_id_len + 36
printc(YELLOW, "-" * dash_len)
printc(YELLOW, f"{'Action':<{max_action_len}} {'LogicalResourceId':<{max_id_len}} {'ResourceType':<{max_resource_len}} Replacement")
printc(YELLOW, "-" * dash_len)
# Print the changes in fixed-width columns
for change in change_set['Changes']:
resource = change['ResourceChange']['ResourceType']
action = change['ResourceChange']['Action']
logical_id = change['ResourceChange']['LogicalResourceId']
replacement = change.get('ResourceChange', {}).get('Replacement', '')
printc(GREEN, f"{action:<{max_action_len}} {logical_id:<{max_id_len}} {resource:<{max_resource_len}} {replacement}")
printc(YELLOW, "-" * dash_len)
printc(YELLOW, '')
else:
printc(GREEN, "No changes detected.")
def print_template_resources(template_resources):
if not template_resources:
printc(GREEN, "None.")
else:
# Calculate the maximum length of each column
max_resource_len = max(len(resource[1]) for resource in template_resources)
max_id_len = max(len(resource[0]) for resource in template_resources)
dash_len = max_resource_len + max_id_len + 17
printc(YELLOW, "")
printc(LIGHT_BLUE, "Template Resources:")
printc(YELLOW, "-" * dash_len)
printc(YELLOW, f"Operation {'LogicalResourceId':<{max_id_len}} {'ResourceType':<{max_resource_len}}")
printc(YELLOW, "-" * dash_len)
# Print the resources in fixed-width columns
for resource in template_resources:
logical_id = resource[0]
resource_type = resource[1]
printc(GREEN, f"+ Add {logical_id:<{max_id_len}} {resource_type:<{max_resource_len}}")
printc(YELLOW, "-" * dash_len)
printc(YELLOW, '')
def parse_template(template):
try:
# Try to parse as JSON
parsed = json.loads(template)
# Extract the resources
resources = parsed.get('Resources', {})
# Create a list of tuples (logical name, type)
resource_list = [(name, details.get('Type')) for name, details in resources.items()]
return resource_list
except json.JSONDecodeError as e:
return parse_yaml_template(template)
def parse_yaml_template(template):
# YAML. Split the template into lines
lines = template.split('\n')
# Remove all empty lines, all lines containing only whitespace, and all lines containing only whitespace followed by a #
lines = [line for line in lines if line.strip() and not line.lstrip().startswith('#')]
# Find the start of the Resources section
resources_start = next((i for i, line in enumerate(lines) if line.startswith('Resources:')), None)
if resources_start is None:
print("No Resources section found.")
return []
# Find the end of the Resources section
resources_end = next((i for i in range(resources_start + 1, len(lines)) if not lines[i].startswith(' ')), len(lines))
# Extract the Resources section
resources_section = lines[resources_start+1:resources_end]
# Determine the number of spaces per indentation level
spaces_per_indent = next((len(line) - len(line.lstrip(' ')) for line in resources_section if line.strip()), None)
if spaces_per_indent is None:
print("No resources found.")
return []
# Extract all logical resource names and their types
resource_list = []
logical_name = None
for line in resources_section:
stripped_line = line.lstrip(' ')
indent_level = (len(line) - len(stripped_line)) // spaces_per_indent
if indent_level == 1 and stripped_line.endswith(':'):
logical_name = stripped_line[:-1]
elif indent_level == 2 and stripped_line.startswith('Type:') and logical_name is not None:
resource_type = stripped_line[len('Type:'):].strip(' "\'')
resource_list.append((logical_name, resource_type))
logical_name = None # Reset logical_name
return resource_list
def update_stack(stack_name, template_body, parameters, capabilities, account_id, region, role, dry_run, verbose):
return process_stack('update', 'stack', stack_name, template_body, parameters, capabilities, account_id, region, role, dry_run, verbose)
def create_stack(stack_name, template_body, parameters, capabilities, account_id, region, role, dry_run, verbose):
return process_stack('create', 'stack', stack_name, template_body, parameters, capabilities, account_id, region, role, dry_run, verbose)
def update_stack_set(stack_set_name, template_body, parameters, capabilities, regions, account_id, region, role, dry_run, verbose):
return process_stack('update', 'stackset', stack_set_name, template_body, parameters, capabilities, account_id, region, role, dry_run, verbose,
OperationPreferences={
'RegionConcurrencyType': 'PARALLEL',
'FailureTolerancePercentage': 0,
'MaxConcurrentPercentage': 100,
'ConcurrencyMode': 'SOFT_FAILURE_TOLERANCE'
})
def create_stack_set(stack_set_name, template_body, parameters, capabilities, root_ou, deployment_regions, account_id, region, role, dry_run, verbose):
return process_stack('create', 'stackset', stack_set_name, template_body, parameters, capabilities, account_id, region, role, dry_run, verbose,
PermissionModel='SERVICE_MANAGED',
AutoDeployment={
'Enabled': True,
'RetainStacksOnAccountRemoval': False
})
def create_stack_set_instances(stack_set_name, template_body, parameters, capabilities, root_ou, except_account, deployment_regions, account_id, region, role, dry_run, verbose):
if dry_run:
printc(YELLOW, f"Dry run enabled. Would have created instances of stack set {stack_set_name} in OU {root_ou} in regions {deployment_regions}.")
return False
cf_client = get_client('cloudformation', account_id, region, role)
# Initialize args
deployment_targets = {
'OrganizationalUnitIds':[root_ou]
}
# Filter away an account if except_account is present
if except_account:
deployment_targets['Accounts'] = [except_account]
deployment_targets['AccountFilterType'] = 'DIFFERENCE'
args = {
'StackSetName': stack_set_name,
'DeploymentTargets': deployment_targets,
'Regions': deployment_regions,
'OperationPreferences': {
'RegionConcurrencyType': 'PARALLEL',
'FailureTolerancePercentage': 0,
'MaxConcurrentPercentage': 100,
'ConcurrencyMode': 'SOFT_FAILURE_TOLERANCE'
}
}
try:
response = cf_client.create_stack_instances(**args)
printc(GREEN, f"Created instances of stack set {stack_set_name} in OU {root_ou} in regions {deployment_regions}.")
return True
except botocore.exceptions.ClientError as e:
printc(RED, f"Failed to create instances of stack set {stack_set_name} in OU {root_ou} in regions {deployment_regions}: {e}")
raise e
def monitor_stack_until_complete(stack_name, account_id, region, role, dry_run, verbose):
"""
Polls the specified CloudFormation stack until it reaches a terminal state.
Parameters:
- stack_name (str): Name of the CloudFormation stack to monitor.
- account_id (str): AWS Account ID to assume the role from.
- region (str): AWS Region where the stack resides.
- role (str): IAM Role to assume for cross-account access.
"""
if dry_run:
return
if verbose:
printc(GRAY, "Waiting for the stack to complete.")
# Get the CloudFormation client using the get_client function
cf_client = get_client('cloudformation', account_id, region, role)
# Define terminal states for CloudFormation stacks and stack sets
terminal_states = ["CREATE_COMPLETE", "ROLLBACK_COMPLETE", "UPDATE_COMPLETE", "UPDATE_ROLLBACK_COMPLETE", "DELETE_COMPLETE", "CURRENT", "ACTIVE", "SKIPPED_SUSPENDED_ACCOUNT"]
# Get the current stack status
stack = cf_client.describe_stacks(StackName=stack_name)
stack_status = stack['Stacks'][0]['StackStatus']
# Return immediately if the stack is already in a terminal state
if stack_status in terminal_states:
return
printc(LIGHT_BLUE, "Waiting for stack or stack set to complete...")
# Save initial line position
print() # Start with a blank line
# Variable to track the previous status
previous_status = None
while True:
try:
# Get the current stack status
stack = cf_client.describe_stacks(StackName=stack_name)
stack_status = stack['Stacks'][0]['StackStatus']
# Only print if status has changed
if stack_status != previous_status:
# Move cursor up if we've printed before
if previous_status:
sys.stdout.write("\033[1F\033[K") # Move up 1 line and clear it
sys.stdout.flush()
# Print the stack status with the appropriate color and reset the color afterward
if "ROLLBACK" in stack_status or "DELETE" in stack_status:
printc(RED, f"Stack Status: {stack_status}")
elif "CREATE_COMPLETE" in stack_status or "UPDATE_COMPLETE" in stack_status:
printc(GREEN, f"Stack Status: {stack_status}")
else:
printc(YELLOW, f"Stack Status: {stack_status}")
# Update previous status
previous_status = stack_status
# Exit loop if the stack is in a terminal state
if stack_status in terminal_states:
time.sleep(5)
break
# Sleep for a shorter interval before checking again
time.sleep(1) # Shorter interval for more frequent checks
except botocore.exceptions.WaiterError as ex:
if ex.last_response.get('Error', {}).get('Code') == 'ThrottlingException':
printc(RED, "API rate limit exceeded. Retrying in 5 seconds...")
time.sleep(5)
else:
raise
except botocore.exceptions.OperationInProgressException as op_in_prog_ex:
printc(RED, f"Another operation is in progress: {op_in_prog_ex}")
printc(RED, "Retrying in 30 seconds...")
time.sleep(30)
def monitor_stackset_until_complete(stackset_name, account_id, region, role, dry_run, verbose):
"""
Polls the specified StackSet until it reaches a terminal state.
Parameters:
- stackset_name (str): Name of the StackSet to monitor.
- account_id (str): AWS Account ID to assume the role from.
- region (str): AWS Region where the StackSet resides.
- role (str): IAM Role to assume for cross-account access.
"""
if dry_run:
return
if verbose:
printc(GRAY, "Waiting for the stackset to complete.")
# Get the CloudFormation client using the get_client function
cf_client = get_client('cloudformation', account_id, region, role)
# Define terminal states for CloudFormation StackSets
terminal_states = ["CREATE_COMPLETE", "ROLLBACK_COMPLETE", "UPDATE_COMPLETE", "UPDATE_ROLLBACK_COMPLETE", "DELETE_COMPLETE", "CURRENT", "ACTIVE", "SKIPPED_SUSPENDED_ACCOUNT"]
# Get the current StackSet status
stackset = cf_client.describe_stack_set(StackSetName=stackset_name)
stackset_status = stackset['StackSet']['Status']
# Return immediately if the StackSet is already in a terminal state
if stackset_status in terminal_states:
return
printc(LIGHT_BLUE, "Waiting for StackSet deployment to complete...")
# Save initial line position
print() # Start with a blank line
# Variable to track the previous status
previous_status = None
while True:
try:
# Get the current StackSet status
stackset = cf_client.describe_stack_set(StackSetName=stackset_name)
stackset_status = stackset['StackSet']['Status']
# Only print if status has changed
if stackset_status != previous_status:
# Move cursor up if we've printed before
if previous_status:
sys.stdout.write("\033[1F\033[K") # Move up 1 line and clear it
sys.stdout.flush()
# Print the StackSet status with the appropriate color and reset the color afterward
if "ROLLBACK" in stackset_status or "DELETE" in stackset_status:
printc(RED, f"StackSet Status: {stackset_status}")
elif "CREATE_COMPLETE" in stackset_status or "UPDATE_COMPLETE" in stackset_status:
printc(GREEN, f"StackSet Status: {stackset_status}")
else:
printc(YELLOW, f"StackSet Status: {stackset_status}")
# Update previous status
previous_status = stackset_status
# Exit loop if the StackSet is in a terminal state
if stackset_status in terminal_states:
time.sleep(5)
break
# Sleep for a shorter interval before checking again
time.sleep(1) # Shorter interval for more frequent checks
except botocore.exceptions.WaiterError as ex:
if ex.last_response.get('Error', {}).get('Code') == 'ThrottlingException':
printc(RED, "API rate limit exceeded. Retrying in 5 seconds...")
time.sleep(5)
else:
raise
except botocore.exceptions.BotoCoreError as error:
printc(RED, f"An error occurred: {error}")
printc(RED, "Retrying in 30 seconds...")
time.sleep(30)
def monitor_stackset_stacks_until_complete(stackset_name, account_id, region, role, dry_run, verbose):
"""
Polls the specified StackSet's stacks until they reach a terminal state.
Parameters:
- stackset_name (str): Name of the StackSet to monitor.
- account_id (str): AWS Account ID to assume the role from.
- region (str): AWS Region where the StackSet resides.
- role (str): IAM Role to assume for cross-account access.
"""
if dry_run:
return
if verbose:
printc(GRAY, "Waiting for the stackset stacks to complete.")
# Get the CloudFormation client using the get_client function
cf_client = get_client('cloudformation', account_id, region, role)
# Define terminal states for CloudFormation stacks
terminal_states = ["CREATE_COMPLETE", "ROLLBACK_COMPLETE", "UPDATE_COMPLETE", "UPDATE_ROLLBACK_COMPLETE", "DELETE_COMPLETE", "CURRENT", "FAILED", "OUTDATED", "SKIPPED_SUSPENDED_ACCOUNT"]
# Get the status of all stacks deployed by the StackSet
stack_instances = cf_client.list_stack_instances(StackSetName=stackset_name)
stack_statuses = [instance['Status'] for instance in stack_instances['Summaries']]
# Return immediately if all stacks are already in a terminal state
if all(status in terminal_states for status in stack_statuses):
return
printc(LIGHT_BLUE, "Waiting for stack set's deployment of its stacks to complete...")
# Track the number of instances in the previous update
previous_instances_count = 0
while True:
try:
# Get the status of all stacks deployed by the StackSet
stack_instances = cf_client.list_stack_instances(StackSetName=stackset_name)
stack_statuses = [instance['Status'] for instance in stack_instances['Summaries']]
# Calculate the number of lines to move up
# If this is not the first iteration, move cursor up by the number of
# previously printed stack instances
if previous_instances_count > 0:
# Clear previous output
sys.stdout.write("\033[F" * previous_instances_count)
sys.stdout.flush()
# Print the status of each stack instance
for instance in stack_instances['Summaries']:
stack_instance_identifier = f"{instance['Account']} {instance['Region']:<15}"
stack_status = instance['Status']
# Clear current line before printing
sys.stdout.write("\033[K")
sys.stdout.flush()
if stack_status in terminal_states:
printc(GREEN, f"{stack_instance_identifier} {stack_status}")
else:
printc(YELLOW, f"{stack_instance_identifier} {stack_status}")
# Update previous instances count
previous_instances_count = len(stack_instances['Summaries'])
# Check if any stack is not in a terminal state
if any(status not in terminal_states for status in stack_statuses):