runbooks 0.2.5__py3-none-any.whl → 0.6.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. conftest.py +26 -0
  2. jupyter-agent/.env.template +2 -0
  3. jupyter-agent/.gitattributes +35 -0
  4. jupyter-agent/README.md +16 -0
  5. jupyter-agent/app.py +256 -0
  6. jupyter-agent/cloudops-agent.png +0 -0
  7. jupyter-agent/ds-system-prompt.txt +154 -0
  8. jupyter-agent/jupyter-agent.png +0 -0
  9. jupyter-agent/llama3_template.jinja +123 -0
  10. jupyter-agent/requirements.txt +9 -0
  11. jupyter-agent/utils.py +409 -0
  12. runbooks/__init__.py +71 -3
  13. runbooks/__main__.py +13 -0
  14. runbooks/aws/ec2_describe_instances.py +1 -1
  15. runbooks/aws/ec2_run_instances.py +8 -2
  16. runbooks/aws/ec2_start_stop_instances.py +17 -4
  17. runbooks/aws/ec2_unused_volumes.py +5 -1
  18. runbooks/aws/s3_create_bucket.py +4 -2
  19. runbooks/aws/s3_list_objects.py +6 -1
  20. runbooks/aws/tagging_lambda_handler.py +13 -2
  21. runbooks/aws/tags.json +12 -0
  22. runbooks/base.py +353 -0
  23. runbooks/cfat/README.md +49 -0
  24. runbooks/cfat/__init__.py +74 -0
  25. runbooks/cfat/app.ts +644 -0
  26. runbooks/cfat/assessment/__init__.py +40 -0
  27. runbooks/cfat/assessment/asana-import.csv +39 -0
  28. runbooks/cfat/assessment/cfat-checks.csv +31 -0
  29. runbooks/cfat/assessment/cfat.txt +520 -0
  30. runbooks/cfat/assessment/collectors.py +200 -0
  31. runbooks/cfat/assessment/jira-import.csv +39 -0
  32. runbooks/cfat/assessment/runner.py +387 -0
  33. runbooks/cfat/assessment/validators.py +290 -0
  34. runbooks/cfat/cli.py +103 -0
  35. runbooks/cfat/docs/asana-import.csv +24 -0
  36. runbooks/cfat/docs/cfat-checks.csv +31 -0
  37. runbooks/cfat/docs/cfat.txt +335 -0
  38. runbooks/cfat/docs/checks-output.png +0 -0
  39. runbooks/cfat/docs/cloudshell-console-run.png +0 -0
  40. runbooks/cfat/docs/cloudshell-download.png +0 -0
  41. runbooks/cfat/docs/cloudshell-output.png +0 -0
  42. runbooks/cfat/docs/downloadfile.png +0 -0
  43. runbooks/cfat/docs/jira-import.csv +24 -0
  44. runbooks/cfat/docs/open-cloudshell.png +0 -0
  45. runbooks/cfat/docs/report-header.png +0 -0
  46. runbooks/cfat/models.py +1026 -0
  47. runbooks/cfat/package-lock.json +5116 -0
  48. runbooks/cfat/package.json +38 -0
  49. runbooks/cfat/report.py +496 -0
  50. runbooks/cfat/reporting/__init__.py +46 -0
  51. runbooks/cfat/reporting/exporters.py +337 -0
  52. runbooks/cfat/reporting/formatters.py +496 -0
  53. runbooks/cfat/reporting/templates.py +135 -0
  54. runbooks/cfat/run-assessment.sh +23 -0
  55. runbooks/cfat/runner.py +69 -0
  56. runbooks/cfat/src/actions/check-cloudtrail-existence.ts +43 -0
  57. runbooks/cfat/src/actions/check-config-existence.ts +37 -0
  58. runbooks/cfat/src/actions/check-control-tower.ts +37 -0
  59. runbooks/cfat/src/actions/check-ec2-existence.ts +46 -0
  60. runbooks/cfat/src/actions/check-iam-users.ts +50 -0
  61. runbooks/cfat/src/actions/check-legacy-cur.ts +30 -0
  62. runbooks/cfat/src/actions/check-org-cloudformation.ts +30 -0
  63. runbooks/cfat/src/actions/check-vpc-existence.ts +43 -0
  64. runbooks/cfat/src/actions/create-asanaimport.ts +14 -0
  65. runbooks/cfat/src/actions/create-backlog.ts +372 -0
  66. runbooks/cfat/src/actions/create-jiraimport.ts +15 -0
  67. runbooks/cfat/src/actions/create-report.ts +616 -0
  68. runbooks/cfat/src/actions/define-account-type.ts +51 -0
  69. runbooks/cfat/src/actions/get-enabled-org-policy-types.ts +40 -0
  70. runbooks/cfat/src/actions/get-enabled-org-services.ts +26 -0
  71. runbooks/cfat/src/actions/get-idc-info.ts +34 -0
  72. runbooks/cfat/src/actions/get-org-da-accounts.ts +34 -0
  73. runbooks/cfat/src/actions/get-org-details.ts +35 -0
  74. runbooks/cfat/src/actions/get-org-member-accounts.ts +44 -0
  75. runbooks/cfat/src/actions/get-org-ous.ts +35 -0
  76. runbooks/cfat/src/actions/get-regions.ts +22 -0
  77. runbooks/cfat/src/actions/zip-assessment.ts +27 -0
  78. runbooks/cfat/src/types/index.d.ts +147 -0
  79. runbooks/cfat/tests/__init__.py +141 -0
  80. runbooks/cfat/tests/test_cli.py +340 -0
  81. runbooks/cfat/tests/test_integration.py +290 -0
  82. runbooks/cfat/tests/test_models.py +505 -0
  83. runbooks/cfat/tests/test_reporting.py +354 -0
  84. runbooks/cfat/tsconfig.json +16 -0
  85. runbooks/cfat/webpack.config.cjs +27 -0
  86. runbooks/config.py +260 -0
  87. runbooks/finops/__init__.py +88 -0
  88. runbooks/finops/aws_client.py +245 -0
  89. runbooks/finops/cli.py +151 -0
  90. runbooks/finops/cost_processor.py +410 -0
  91. runbooks/finops/dashboard_runner.py +448 -0
  92. runbooks/finops/helpers.py +355 -0
  93. runbooks/finops/main.py +14 -0
  94. runbooks/finops/profile_processor.py +174 -0
  95. runbooks/finops/types.py +66 -0
  96. runbooks/finops/visualisations.py +80 -0
  97. runbooks/inventory/.gitignore +354 -0
  98. runbooks/inventory/ArgumentsClass.py +261 -0
  99. runbooks/inventory/Inventory_Modules.py +6130 -0
  100. runbooks/inventory/LandingZone/delete_lz.py +1075 -0
  101. runbooks/inventory/README.md +1320 -0
  102. runbooks/inventory/__init__.py +62 -0
  103. runbooks/inventory/account_class.py +532 -0
  104. runbooks/inventory/all_my_instances_wrapper.py +123 -0
  105. runbooks/inventory/aws_decorators.py +201 -0
  106. runbooks/inventory/cfn_move_stack_instances.py +1526 -0
  107. runbooks/inventory/check_cloudtrail_compliance.py +614 -0
  108. runbooks/inventory/check_controltower_readiness.py +1107 -0
  109. runbooks/inventory/check_landingzone_readiness.py +711 -0
  110. runbooks/inventory/cloudtrail.md +727 -0
  111. runbooks/inventory/collectors/__init__.py +20 -0
  112. runbooks/inventory/collectors/aws_compute.py +518 -0
  113. runbooks/inventory/collectors/aws_networking.py +275 -0
  114. runbooks/inventory/collectors/base.py +222 -0
  115. runbooks/inventory/core/__init__.py +19 -0
  116. runbooks/inventory/core/collector.py +303 -0
  117. runbooks/inventory/core/formatter.py +296 -0
  118. runbooks/inventory/delete_s3_buckets_objects.py +169 -0
  119. runbooks/inventory/discovery.md +81 -0
  120. runbooks/inventory/draw_org_structure.py +748 -0
  121. runbooks/inventory/ec2_vpc_utils.py +341 -0
  122. runbooks/inventory/find_cfn_drift_detection.py +272 -0
  123. runbooks/inventory/find_cfn_orphaned_stacks.py +719 -0
  124. runbooks/inventory/find_cfn_stackset_drift.py +733 -0
  125. runbooks/inventory/find_ec2_security_groups.py +669 -0
  126. runbooks/inventory/find_landingzone_versions.py +201 -0
  127. runbooks/inventory/find_vpc_flow_logs.py +1221 -0
  128. runbooks/inventory/inventory.sh +659 -0
  129. runbooks/inventory/list_cfn_stacks.py +558 -0
  130. runbooks/inventory/list_cfn_stackset_operation_results.py +252 -0
  131. runbooks/inventory/list_cfn_stackset_operations.py +734 -0
  132. runbooks/inventory/list_cfn_stacksets.py +453 -0
  133. runbooks/inventory/list_config_recorders_delivery_channels.py +681 -0
  134. runbooks/inventory/list_ds_directories.py +354 -0
  135. runbooks/inventory/list_ec2_availability_zones.py +286 -0
  136. runbooks/inventory/list_ec2_ebs_volumes.py +244 -0
  137. runbooks/inventory/list_ec2_instances.py +425 -0
  138. runbooks/inventory/list_ecs_clusters_and_tasks.py +562 -0
  139. runbooks/inventory/list_elbs_load_balancers.py +411 -0
  140. runbooks/inventory/list_enis_network_interfaces.py +526 -0
  141. runbooks/inventory/list_guardduty_detectors.py +568 -0
  142. runbooks/inventory/list_iam_policies.py +404 -0
  143. runbooks/inventory/list_iam_roles.py +518 -0
  144. runbooks/inventory/list_iam_saml_providers.py +359 -0
  145. runbooks/inventory/list_lambda_functions.py +882 -0
  146. runbooks/inventory/list_org_accounts.py +446 -0
  147. runbooks/inventory/list_org_accounts_users.py +354 -0
  148. runbooks/inventory/list_rds_db_instances.py +406 -0
  149. runbooks/inventory/list_route53_hosted_zones.py +318 -0
  150. runbooks/inventory/list_servicecatalog_provisioned_products.py +575 -0
  151. runbooks/inventory/list_sns_topics.py +360 -0
  152. runbooks/inventory/list_ssm_parameters.py +402 -0
  153. runbooks/inventory/list_vpc_subnets.py +433 -0
  154. runbooks/inventory/list_vpcs.py +422 -0
  155. runbooks/inventory/lockdown_cfn_stackset_role.py +224 -0
  156. runbooks/inventory/models/__init__.py +24 -0
  157. runbooks/inventory/models/account.py +192 -0
  158. runbooks/inventory/models/inventory.py +309 -0
  159. runbooks/inventory/models/resource.py +247 -0
  160. runbooks/inventory/recover_cfn_stack_ids.py +205 -0
  161. runbooks/inventory/requirements.txt +12 -0
  162. runbooks/inventory/run_on_multi_accounts.py +211 -0
  163. runbooks/inventory/tests/common_test_data.py +3661 -0
  164. runbooks/inventory/tests/common_test_functions.py +204 -0
  165. runbooks/inventory/tests/script_test_data.py +0 -0
  166. runbooks/inventory/tests/setup.py +24 -0
  167. runbooks/inventory/tests/src.py +18 -0
  168. runbooks/inventory/tests/test_cfn_describe_stacks.py +208 -0
  169. runbooks/inventory/tests/test_ec2_describe_instances.py +162 -0
  170. runbooks/inventory/tests/test_inventory_modules.py +55 -0
  171. runbooks/inventory/tests/test_lambda_list_functions.py +86 -0
  172. runbooks/inventory/tests/test_moto_integration_example.py +273 -0
  173. runbooks/inventory/tests/test_org_list_accounts.py +49 -0
  174. runbooks/inventory/update_aws_actions.py +173 -0
  175. runbooks/inventory/update_cfn_stacksets.py +1215 -0
  176. runbooks/inventory/update_cloudwatch_logs_retention_policy.py +294 -0
  177. runbooks/inventory/update_iam_roles_cross_accounts.py +478 -0
  178. runbooks/inventory/update_s3_public_access_block.py +539 -0
  179. runbooks/inventory/utils/__init__.py +23 -0
  180. runbooks/inventory/utils/aws_helpers.py +510 -0
  181. runbooks/inventory/utils/threading_utils.py +493 -0
  182. runbooks/inventory/utils/validation.py +682 -0
  183. runbooks/inventory/verify_ec2_security_groups.py +1430 -0
  184. runbooks/main.py +785 -0
  185. runbooks/organizations/__init__.py +12 -0
  186. runbooks/organizations/manager.py +374 -0
  187. runbooks/security_baseline/README.md +324 -0
  188. runbooks/security_baseline/checklist/alternate_contacts.py +8 -1
  189. runbooks/security_baseline/checklist/bucket_public_access.py +4 -1
  190. runbooks/security_baseline/checklist/cloudwatch_alarm_configuration.py +9 -2
  191. runbooks/security_baseline/checklist/guardduty_enabled.py +9 -2
  192. runbooks/security_baseline/checklist/multi_region_instance_usage.py +5 -1
  193. runbooks/security_baseline/checklist/root_access_key.py +6 -1
  194. runbooks/security_baseline/config-origin.json +1 -1
  195. runbooks/security_baseline/config.json +1 -1
  196. runbooks/security_baseline/permission.json +1 -1
  197. runbooks/security_baseline/report_generator.py +10 -2
  198. runbooks/security_baseline/report_template_en.html +7 -7
  199. runbooks/security_baseline/report_template_jp.html +7 -7
  200. runbooks/security_baseline/report_template_kr.html +12 -12
  201. runbooks/security_baseline/report_template_vn.html +7 -7
  202. runbooks/security_baseline/requirements.txt +7 -0
  203. runbooks/security_baseline/run_script.py +8 -2
  204. runbooks/security_baseline/security_baseline_tester.py +10 -2
  205. runbooks/security_baseline/utils/common.py +5 -1
  206. runbooks/utils/__init__.py +204 -0
  207. runbooks-0.6.1.dist-info/METADATA +373 -0
  208. runbooks-0.6.1.dist-info/RECORD +237 -0
  209. {runbooks-0.2.5.dist-info → runbooks-0.6.1.dist-info}/WHEEL +1 -1
  210. runbooks-0.6.1.dist-info/entry_points.txt +7 -0
  211. runbooks-0.6.1.dist-info/licenses/LICENSE +201 -0
  212. runbooks-0.6.1.dist-info/top_level.txt +3 -0
  213. runbooks/python101/calculator.py +0 -34
  214. runbooks/python101/config.py +0 -1
  215. runbooks/python101/exceptions.py +0 -16
  216. runbooks/python101/file_manager.py +0 -218
  217. runbooks/python101/toolkit.py +0 -153
  218. runbooks-0.2.5.dist-info/METADATA +0 -439
  219. runbooks-0.2.5.dist-info/RECORD +0 -61
  220. runbooks-0.2.5.dist-info/entry_points.txt +0 -3
  221. runbooks-0.2.5.dist-info/top_level.txt +0 -1
@@ -0,0 +1,453 @@
1
+ #!/usr/bin/env python3
2
+
3
+ """
4
+ AWS CloudFormation StackSets Discovery and Analysis Script
5
+
6
+ This script provides comprehensive discovery and analysis capabilities for AWS CloudFormation
7
+ StackSets across multi-account AWS Organizations environments. It's designed for enterprise
8
+ cloud governance teams who need visibility into multi-account infrastructure deployment patterns,
9
+ StackSet lifecycle management, and centralized infrastructure orchestration across organizational
10
+ boundaries with detailed instance enumeration and operational oversight.
11
+
12
+ Key Features:
13
+ - Multi-account CloudFormation StackSet discovery using assume role capabilities
14
+ - Cross-region StackSet enumeration with comprehensive metadata extraction
15
+ - StackSet instance counting and detailed deployment analysis
16
+ - Fragment-based search for targeted StackSet discovery and filtering
17
+ - Status-based filtering for active and deleted StackSet lifecycle tracking
18
+ - Single-profile authentication with support for federated Organizations access
19
+ - Enterprise reporting with CSV export and structured output
20
+
21
+ Enterprise Use Cases:
22
+ - Multi-account infrastructure governance and StackSet portfolio management
23
+ - Centralized deployment pattern analysis and standardization oversight
24
+ - StackSet lifecycle tracking for operational excellence and compliance
25
+ - Infrastructure drift detection through StackSet status monitoring
26
+ - Cost optimization through StackSet deployment pattern analysis
27
+ - Compliance auditing for multi-account infrastructure governance
28
+ - Disaster recovery planning through StackSet deployment topology mapping
29
+
30
+ StackSet Management Features:
31
+ - Comprehensive StackSet enumeration with status and metadata tracking
32
+ - StackSet instance discovery with detailed deployment topology analysis
33
+ - Fragment-based search for targeted StackSet identification and management
34
+ - Status filtering for active, deleted, and lifecycle transition tracking
35
+ - Cross-account StackSet visibility for organizational infrastructure oversight
36
+ - Regional StackSet deployment pattern analysis and optimization
37
+
38
+ Security Considerations:
39
+ - Uses assume role capabilities for cross-account StackSet discovery
40
+ - Implements proper error handling for authorization failures
41
+ - Supports read-only operations with no StackSet modification capabilities
42
+ - Respects CloudFormation permissions and regional access constraints
43
+ - Provides comprehensive audit trail through detailed logging
44
+ - Sensitive infrastructure information handling with appropriate access controls
45
+
46
+ Performance Considerations:
47
+ - Sequential processing for reliable StackSet discovery operations
48
+ - Optional StackSet instance enumeration with performance timing metrics
49
+ - Progress tracking for operational visibility during discovery
50
+ - Efficient credential management for cross-account StackSet access
51
+ - Memory-optimized data structures for large StackSet inventories
52
+
53
+ StackSet Instance Analysis:
54
+ - Optional detailed instance enumeration for deployment topology mapping
55
+ - Instance count tracking for capacity planning and optimization
56
+ - Cross-account instance distribution analysis for governance oversight
57
+ - Regional instance deployment pattern analysis and standardization
58
+ - Instance status tracking for operational excellence and monitoring
59
+
60
+ Dependencies:
61
+ - boto3/botocore for AWS CloudFormation StackSets API interactions
62
+ - account_class for AWS account access management
63
+ - ArgumentsClass for standardized CLI argument parsing
64
+ - Inventory_Modules for common utility functions and StackSet discovery
65
+ - colorama for enhanced output formatting
66
+
67
+ Compliance and Audit Features:
68
+ - Comprehensive StackSet discovery for infrastructure governance auditing
69
+ - StackSet deployment pattern analysis for compliance validation
70
+ - Cross-account infrastructure visibility for organizational security oversight
71
+ - StackSet lifecycle tracking for governance and compliance management
72
+ - Infrastructure standardization analysis for organizational oversight
73
+
74
+ Future Enhancements:
75
+ - Multi-threading for improved performance across large organizations
76
+ - StackSet drift detection and configuration analysis
77
+ - Integration with AWS Config for StackSet configuration monitoring
78
+ - StackSet optimization recommendations for governance and cost management
79
+
80
+ Author: AWS CloudOps Team
81
+ Version: 2024.06.20
82
+ """
83
+
84
+ import logging
85
+ import sys
86
+ from os.path import split
87
+ from time import time
88
+
89
+ from account_class import aws_acct_access
90
+ from ArgumentsClass import CommonArguments
91
+ from colorama import Fore, init
92
+ from Inventory_Modules import (
93
+ RemoveCoreAccounts,
94
+ display_results,
95
+ find_stack_instances2,
96
+ find_stacksets2,
97
+ get_credentials_for_accounts_in_org,
98
+ get_regions3,
99
+ )
100
+
101
+ init()
102
+
103
+ __version__ = "2024.06.20"
104
+ begin_time = time()
105
+ ERASE_LINE = "\x1b[2K"
106
+
107
+ #####################
108
+ # Functions
109
+ #####################
110
+
111
+
112
+ def parse_args(args):
113
+ """
114
+ Parse command line arguments for AWS CloudFormation StackSets discovery and analysis operations.
115
+
116
+ Configures comprehensive argument parsing for single-profile, multi-region CloudFormation StackSet
117
+ discovery operations. Supports enterprise infrastructure governance with profile management,
118
+ region targeting, fragment-based search, and StackSet instance analysis for multi-account
119
+ deployment pattern oversight and centralized infrastructure orchestration.
120
+
121
+ Args:
122
+ args (list): Command line arguments from sys.argv[1:]
123
+
124
+ Returns:
125
+ argparse.Namespace: Parsed arguments containing:
126
+ - Profile: AWS profile for authentication
127
+ - Regions: Target regions for StackSet discovery
128
+ - Fragments: StackSet name fragments for targeted search
129
+ - Exact: Enable exact fragment matching
130
+ - SkipAccounts: Accounts to exclude from discovery
131
+ - AccessRoles: Cross-account roles for Organizations access
132
+ - RootOnly: Limit to organization root accounts
133
+ - Filename: Output file for CSV export
134
+ - Time: Enable performance timing metrics
135
+ - loglevel: Logging verbosity configuration
136
+ - pinstancecount: Enable StackSet instance enumeration
137
+ - pstatus: StackSet status filter (Active/Deleted)
138
+
139
+ Configuration Options:
140
+ - Single profile support for focused StackSet discovery operations
141
+ - Multi-region targeting for comprehensive StackSet infrastructure analysis
142
+ - Fragment-based search for targeted StackSet identification and filtering
143
+ - Extended arguments for advanced filtering and account selection
144
+ - Role-based access for cross-account StackSet operations
145
+ - Root-only mode for organization-level StackSet inventory
146
+ - File output for integration with infrastructure management tools
147
+ - Timing metrics for performance optimization and monitoring
148
+ - Verbose logging for debugging and infrastructure governance audit
149
+
150
+ StackSet-Specific Features:
151
+ - Instance counting (-i/--instances): Enables detailed StackSet instance enumeration
152
+ for deployment topology analysis and capacity planning
153
+ - Status filtering (-s/--status): Filters StackSets by lifecycle status including:
154
+ - Active: Currently deployed and operational StackSets
155
+ - Deleted: Previously deployed but now deleted StackSets for cleanup analysis
156
+ - Fragment search: Targeted StackSet discovery using name pattern matching
157
+
158
+ Enterprise Infrastructure Management:
159
+ - Multi-account StackSet visibility for organizational governance oversight
160
+ - Cross-region StackSet deployment pattern analysis and standardization
161
+ - StackSet lifecycle tracking for operational excellence and compliance
162
+ - Infrastructure governance and centralized deployment orchestration
163
+ """
164
+ script_path, script_name = split(sys.argv[0])
165
+ parser = CommonArguments()
166
+ parser.singleprofile() # Single profile for focused StackSet discovery operations
167
+ parser.multiregion() # Multi-region support for comprehensive StackSet infrastructure analysis
168
+ parser.fragment() # Fragment-based search for targeted StackSet identification
169
+ parser.extendedargs() # Extended arguments for advanced filtering and account selection
170
+ parser.rolestouse() # Role-based access for cross-account StackSet operations
171
+ parser.rootOnly() # Root-only mode for organization-level StackSet inventory
172
+ parser.save_to_file() # File output for integration with infrastructure management tools
173
+ parser.timing() # Timing metrics for performance optimization and monitoring
174
+ parser.verbosity() # Verbose logging for debugging and infrastructure governance audit
175
+ parser.version(__version__)
176
+ local = parser.my_parser.add_argument_group(script_name, "Parameters specific to this script")
177
+ local.add_argument(
178
+ "-i",
179
+ "--instances",
180
+ dest="pinstancecount",
181
+ action="store_true",
182
+ default=False,
183
+ help="Enable detailed StackSet instance enumeration for deployment topology analysis and capacity planning",
184
+ )
185
+ local.add_argument(
186
+ "-s",
187
+ "--status",
188
+ dest="pstatus",
189
+ metavar="CloudFormation status",
190
+ default="Active",
191
+ choices=["active", "ACTIVE", "Active", "deleted", "DELETED", "Deleted"],
192
+ help="Filter StackSets by lifecycle status - 'ACTIVE' for operational StackSets or 'DELETED' for cleanup analysis",
193
+ )
194
+ return parser.my_parser.parse_args(args)
195
+
196
+
197
+ def setup_auth_accounts_and_regions(fProfile: str) -> (aws_acct_access, list, list):
198
+ """
199
+ Initialize authentication and discover AWS Organizations accounts and regions for StackSet operations.
200
+
201
+ Establishes authentication context and discovers organizational structure for comprehensive
202
+ CloudFormation StackSet discovery across multi-account environments. Performs account
203
+ filtering, region validation, and access role configuration for enterprise infrastructure
204
+ governance and centralized deployment orchestration.
205
+
206
+ Args:
207
+ fProfile (str): AWS profile name for authentication and Organizations access
208
+ If None, uses default profile or credential chain
209
+
210
+ Returns:
211
+ tuple: Three-element tuple containing:
212
+ - aws_acct_access: Authenticated account access object for Organizations operations
213
+ - list: Account IDs available for StackSet discovery and analysis
214
+ - list: Valid AWS regions for StackSet infrastructure operations
215
+
216
+ Authentication and Discovery:
217
+ - Establishes AWS Organizations access using the specified profile
218
+ - Discovers child accounts within the organization structure
219
+ - Validates regional access and availability for StackSet operations
220
+ - Applies account filtering based on skip lists and inclusion criteria
221
+
222
+ Account Management:
223
+ - Removes core accounts from discovery scope based on skip configuration
224
+ - Applies account inclusion filters for targeted StackSet analysis
225
+ - Supports root-only mode for organization-level StackSet inventory
226
+ - Handles access role configuration for cross-account StackSet operations
227
+
228
+ Enterprise Features:
229
+ - Multi-account discovery for organizational StackSet governance
230
+ - Regional validation for comprehensive StackSet infrastructure analysis
231
+ - Account filtering for targeted infrastructure discovery and management
232
+ - Access role configuration for enterprise security and compliance
233
+
234
+ Error Handling:
235
+ - Connection error detection with appropriate system exit
236
+ - Profile validation and authentication failure management
237
+ - Regional access validation for StackSet operations
238
+ - Comprehensive error logging for troubleshooting
239
+ """
240
+ try:
241
+ # Establish AWS Organizations access using the specified profile
242
+ aws_acct = aws_acct_access(fProfile)
243
+ except ConnectionError as my_Error:
244
+ # Handle authentication and connection failures with appropriate logging
245
+ logging.error(f"Exiting due to error: {my_Error}")
246
+ sys.exit(8)
247
+
248
+ # Discover child accounts within the organization structure
249
+ ChildAccounts = aws_acct.ChildAccounts
250
+
251
+ # Validate regional access and availability for StackSet operations
252
+ RegionList = get_regions3(aws_acct, pRegionList)
253
+
254
+ # Apply account filtering based on skip lists and core account exclusions
255
+ ChildAccounts = RemoveCoreAccounts(ChildAccounts, pSkipAccounts)
256
+
257
+ # Determine final account list based on inclusion criteria and access configuration
258
+ if pAccountList is None:
259
+ # Include all discovered child accounts when no specific list provided
260
+ AccountList = [account["AccountId"] for account in ChildAccounts]
261
+ elif pAccessRoles is not None:
262
+ # Use provided account list when access roles are specified
263
+ AccountList = pAccountList
264
+ else:
265
+ # Filter child accounts to include only those in the specified account list
266
+ AccountList = [account["AccountId"] for account in ChildAccounts if account["AccountId"] in pAccountList]
267
+
268
+ # Display discovery scope and configuration for operational transparency
269
+ print(f"You asked to find CloudFormation stacksets")
270
+ if pRootOnly:
271
+ print(f"\tIn only the root account: {aws_acct.acct_number}")
272
+ else:
273
+ print(f"\tin these accounts: {Fore.RED}{AccountList}{Fore.RESET}")
274
+ print(f"\tin these regions: {Fore.RED}{RegionList}{Fore.RESET}")
275
+ print(
276
+ f"\tContaining {'this ' + Fore.RED + 'exact fragment' + Fore.RESET if pExact else 'one of these fragments'}: {pFragments}"
277
+ )
278
+ if pSkipAccounts is not None:
279
+ print(f"\tWhile skipping these accounts: {Fore.RED}{pSkipAccounts}{Fore.RESET}")
280
+
281
+ return aws_acct, AccountList, RegionList
282
+
283
+
284
+ def find_all_cfnstacksets(f_All_Credentials: list, f_Fragments: list, f_Status) -> list:
285
+ """
286
+ Discover and enumerate CloudFormation StackSets across multiple AWS accounts and regions.
287
+
288
+ Performs comprehensive StackSet discovery using sequential processing to efficiently inventory
289
+ StackSets across enterprise AWS environments. Supports fragment-based filtering for targeted
290
+ discovery and optional instance enumeration for deployment topology analysis and capacity planning.
291
+
292
+ Args:
293
+ f_All_Credentials (list): List of credential dictionaries for cross-account access containing:
294
+ - AccountId: AWS account number
295
+ - Region: Target AWS region
296
+ - Success: Boolean indicating credential validity
297
+ - AccessError: Error details for failed credential attempts
298
+ f_Fragments (list): StackSet name fragments for targeted search and filtering
299
+ f_Status (str): StackSet status filter ('Active' or 'Deleted')
300
+
301
+ Returns:
302
+ list: Comprehensive list of StackSet dictionaries containing:
303
+ - AccountId: AWS account containing the StackSet
304
+ - Region: AWS region where StackSet is managed
305
+ - StackName: CloudFormation StackSet name identifier
306
+ - Status: StackSet operational status
307
+ - InstanceNum: Number of StackSet instances (if enumeration enabled)
308
+
309
+ StackSet Discovery Features:
310
+ - Comprehensive StackSet enumeration with status and metadata tracking
311
+ - Fragment-based search for targeted StackSet identification and filtering
312
+ - Status filtering for active and deleted StackSet lifecycle tracking
313
+ - Optional StackSet instance enumeration for deployment topology analysis
314
+ - Cross-account StackSet visibility for organizational infrastructure oversight
315
+
316
+ Performance Considerations:
317
+ - Sequential processing for reliable StackSet discovery operations
318
+ - Progress tracking for operational visibility during discovery
319
+ - Optional instance enumeration with performance timing metrics
320
+ - Efficient credential management for cross-account StackSet access
321
+ - Graceful error handling for authorization and access failures
322
+
323
+ Enterprise Infrastructure Governance:
324
+ - Multi-account StackSet discovery for organizational oversight
325
+ - StackSet deployment pattern analysis and standardization
326
+ - Infrastructure lifecycle tracking for operational excellence
327
+ - Centralized deployment orchestration visibility and management
328
+
329
+ Error Handling:
330
+ - Authorization failure detection with appropriate logging
331
+ - AWS API error management with graceful degradation
332
+ - Credential validation and failure tracking
333
+ - Comprehensive error reporting for troubleshooting
334
+ """
335
+ All_Results = []
336
+ for credential in f_All_Credentials:
337
+ if not credential["Success"]:
338
+ logging.error(
339
+ f"Failure for account {credential['AccountId']} in region {credential['Region']}\n"
340
+ f"With message: {credential['AccessError']}"
341
+ )
342
+ continue
343
+ # logging.info(f"Account Creds: {account_credentials}")
344
+ # Display progress for operational visibility during StackSet discovery
345
+ print(
346
+ f"{ERASE_LINE}{Fore.RED}Checking Account: {credential['AccountId']} Region: {credential['Region']} for stacksets matching {f_Fragments} with status: {f_Status}{Fore.RESET}",
347
+ end="\r",
348
+ )
349
+
350
+ # Call inventory module to discover StackSets using fragment and status filtering
351
+ StackSets = find_stacksets2(credential, pFragments, pstatus)
352
+ logging.warning(
353
+ f"Account: {credential['AccountId']} | Region: {credential['Region']} | Found {len(StackSets)} Stacksets"
354
+ )
355
+
356
+ # Handle cases where no StackSets are found in the account/region combination
357
+ if not StackSets:
358
+ print(
359
+ f"{ERASE_LINE}We connected to account {credential['AccountId']} in region {credential['Region']}, but found no stacksets",
360
+ end="\r",
361
+ ) if verbose < 50 else ""
362
+ else:
363
+ print(
364
+ f"{ERASE_LINE}{Fore.RED}Account: {credential['AccountId']} Region: {credential['Region']} Found {len(StackSets)} Stacksets{Fore.RESET}",
365
+ end="\r",
366
+ ) if verbose < 50 else ""
367
+
368
+ # Process each discovered StackSet with optional instance enumeration
369
+ for stack in StackSets:
370
+ ListOfStackInstances = [] # Reset instance list for each StackSet
371
+
372
+ # Optional StackSet instance enumeration for deployment topology analysis
373
+ if pInstanceCount:
374
+ milestone = time()
375
+ # Discover StackSet instances across accounts and regions for capacity planning
376
+ ListOfStackInstances = find_stack_instances2(credential, credential["Region"], stack["StackSetName"])
377
+ if pTiming:
378
+ print(
379
+ f"{ERASE_LINE}Found {len(ListOfStackInstances)} instances for {stack['StackSetName']} in {credential['Region']}, which took {time() - milestone:.2f} seconds",
380
+ end="\r",
381
+ )
382
+
383
+ # Aggregate StackSet information for enterprise infrastructure governance
384
+ All_Results.append(
385
+ {
386
+ "AccountId": credential["AccountId"],
387
+ "StackName": stack["StackSetName"],
388
+ "Status": stack["Status"],
389
+ "Region": credential["Region"],
390
+ "InstanceNum": len(ListOfStackInstances) if pInstanceCount else "N/A",
391
+ }
392
+ )
393
+ return All_Results
394
+
395
+
396
+ #####################
397
+ # Main
398
+ #####################
399
+
400
+ if __name__ == "__main__":
401
+ args = parse_args(sys.argv[1:])
402
+ pProfile = args.Profile
403
+ pRegionList = args.Regions
404
+ pInstanceCount = args.pinstancecount
405
+ pRootOnly = args.RootOnly
406
+ pSkipAccounts = args.SkipAccounts
407
+ pSkipProfiles = args.SkipProfiles
408
+ pAccountList = args.Accounts
409
+ pAccessRoles = args.AccessRoles
410
+ verbose = args.loglevel
411
+ pTiming = args.Time
412
+ pFragments = args.Fragments
413
+ pExact = args.Exact
414
+ pstatus = args.pstatus
415
+ pFilename = args.Filename
416
+ # Setup logging levels
417
+ logging.basicConfig(level=verbose, format="[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s")
418
+ logging.getLogger("boto3").setLevel(logging.CRITICAL)
419
+ logging.getLogger("botocore").setLevel(logging.CRITICAL)
420
+ logging.getLogger("s3transfer").setLevel(logging.CRITICAL)
421
+ logging.getLogger("urllib3").setLevel(logging.CRITICAL)
422
+
423
+ # Setup auth object, get account list and region list setup
424
+ aws_acct, AccountList, RegionList = setup_auth_accounts_and_regions(pProfile)
425
+ # Get all credentials needed
426
+ CredentialList = get_credentials_for_accounts_in_org(
427
+ aws_acct, pSkipAccounts, pRootOnly, AccountList, pProfile, RegionList, pAccessRoles, pTiming
428
+ )
429
+ # Find all the stacksets
430
+ All_Results = find_all_cfnstacksets(CredentialList, AccountList, RegionList)
431
+ print()
432
+ display_dict = {
433
+ "AccountId": {"DisplayOrder": 1, "Heading": "Acct Number"},
434
+ "Region": {"DisplayOrder": 2, "Heading": "Region"},
435
+ "Status": {"DisplayOrder": 3, "Heading": "Status"},
436
+ "StackName": {"DisplayOrder": 4, "Heading": "Stackset Name"},
437
+ }
438
+ if pInstanceCount:
439
+ display_dict.update({"Instances": {"DisplayOrder": 5, "Heading": "# of Instances"}})
440
+
441
+ # Display results
442
+ display_results(All_Results, display_dict, None, pFilename)
443
+
444
+ print(ERASE_LINE)
445
+ print(
446
+ f"{Fore.RED}Found {len(All_Results)} Stacksets across {len(AccountList)} accounts across {len(RegionList)} regions{Fore.RESET}"
447
+ )
448
+ print()
449
+ if pTiming:
450
+ print(ERASE_LINE)
451
+ print(f"{Fore.GREEN}This script took {time() - begin_time:.2f} seconds{Fore.RESET}")
452
+ print("Thanks for using this script...")
453
+ print()