runbooks 0.2.3__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 +8 -8
  199. runbooks/security_baseline/report_template_jp.html +8 -8
  200. runbooks/security_baseline/report_template_kr.html +13 -13
  201. runbooks/security_baseline/report_template_vn.html +8 -8
  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.3.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.3.dist-info/METADATA +0 -435
  219. runbooks-0.2.3.dist-info/RECORD +0 -61
  220. runbooks-0.2.3.dist-info/entry_points.txt +0 -3
  221. runbooks-0.2.3.dist-info/top_level.txt +0 -1
@@ -0,0 +1,562 @@
1
+ # !/usr/bin/env python3
2
+
3
+ """
4
+ AWS ECS Clusters, Services, and Tasks Discovery and Analysis Script
5
+
6
+ This script provides comprehensive discovery and inventory capabilities for Amazon
7
+ Elastic Container Service (ECS) resources across multiple AWS accounts and regions.
8
+ It's designed for enterprise container platform teams who need visibility into
9
+ containerized workloads, service distribution, and task management across large-scale
10
+ AWS deployments.
11
+
12
+ Key Features:
13
+ - Multi-account ECS cluster discovery using assume role capabilities
14
+ - Multi-region scanning with configurable region targeting
15
+ - ECS service enumeration with detailed metadata extraction
16
+ - ECS task inventory with state tracking and resource utilization
17
+ - Container workload analysis and capacity planning support
18
+ - Enterprise reporting with CSV export and structured output
19
+ - Profile-based authentication with support for federated access
20
+
21
+ Enterprise Use Cases:
22
+ - Container platform inventory and governance across organizations
23
+ - ECS service distribution analysis for load balancing optimization
24
+ - Task resource utilization tracking for cost optimization
25
+ - Capacity planning for containerized workloads
26
+ - Compliance reporting for container security and configuration standards
27
+ - Multi-account container orchestration visibility
28
+ - Disaster recovery planning with service distribution analysis
29
+
30
+ Container Platform Features:
31
+ - ECS cluster enumeration with capacity provider analysis
32
+ - Service discovery with task definition and deployment tracking
33
+ - Task inventory with container instance placement and resource allocation
34
+ - Service health monitoring and availability analysis
35
+ - Container resource utilization tracking across accounts
36
+ - Load balancer integration analysis for service endpoints
37
+
38
+ Security Considerations:
39
+ - Uses IAM assume role capabilities for cross-account ECS access
40
+ - Implements proper error handling for authorization failures
41
+ - Supports read-only operations with no container modification capabilities
42
+ - Respects ECS service permissions and cluster access constraints
43
+ - Provides comprehensive audit trail through detailed logging
44
+
45
+ ECS Resource Analysis:
46
+ - Cluster capacity and utilization metrics for planning
47
+ - Service scaling configuration and deployment strategy analysis
48
+ - Task placement constraints and resource requirements tracking
49
+ - Container instance distribution across availability zones
50
+ - Service mesh and load balancer integration visibility
51
+
52
+ Performance Considerations:
53
+ - Multi-threaded processing for concurrent ECS API operations
54
+ - Progress tracking with tqdm for operational visibility during long operations
55
+ - Efficient credential management for cross-account container access
56
+ - Memory-optimized data structures for large container inventories
57
+ - Queue-based worker architecture for scalable discovery operations
58
+
59
+ Threading Architecture:
60
+ - Worker thread pool with configurable concurrency (max 25 threads)
61
+ - Queue-based task distribution for efficient resource discovery
62
+ - Thread-safe error handling and progress tracking
63
+ - Graceful degradation for account access failures
64
+
65
+ Dependencies:
66
+ - boto3/botocore for AWS ECS API interactions
67
+ - Inventory_Modules for common utility functions and credential management
68
+ - ArgumentsClass for standardized CLI argument parsing
69
+ - threading and queue for concurrent processing architecture
70
+ - colorama for enhanced output formatting and tqdm for progress tracking
71
+
72
+ Future Enhancements:
73
+ - ECS task definition analysis and security compliance checking
74
+ - Container image vulnerability scanning integration
75
+ - Service mesh configuration analysis
76
+ - Auto-scaling configuration and recommendation engine
77
+ - Cost optimization recommendations based on resource utilization
78
+
79
+ Author: AWS CloudOps Team
80
+ Version: 2024.09.06
81
+ """
82
+
83
+ import logging
84
+ import sys
85
+ from os.path import split
86
+ from queue import Queue
87
+ from threading import Thread
88
+ from time import time
89
+
90
+ import Inventory_Modules
91
+ from ArgumentsClass import CommonArguments
92
+ from botocore.exceptions import ClientError
93
+ from colorama import Fore, init
94
+ from Inventory_Modules import display_results, find_account_ecs_clusters_services_and_tasks2, get_all_credentials
95
+ from tqdm.auto import tqdm
96
+
97
+ init()
98
+ __version__ = "2024.09.06"
99
+ ERASE_LINE = "\x1b[2K"
100
+ begin_time = time()
101
+
102
+ # TODO: Need a table at the bottom that summarizes the results, by instance-type, by running/ stopped, maybe by account and region
103
+
104
+
105
+ ##################
106
+ # Functions
107
+ ##################
108
+
109
+
110
+ def parse_args(f_arguments):
111
+ """
112
+ Parse command line arguments for ECS clusters, services, and tasks discovery operations.
113
+
114
+ Configures comprehensive argument parsing for multi-account, multi-region ECS resource
115
+ inventory operations. Supports enterprise container platform management with profile
116
+ management, region targeting, organizational access controls, and status filtering for
117
+ container workload analysis and capacity planning.
118
+
119
+ Args:
120
+ f_arguments (list): Command line arguments from sys.argv[1:]
121
+
122
+ Returns:
123
+ argparse.Namespace: Parsed arguments containing:
124
+ - Profiles: List of AWS profiles to process
125
+ - Regions: Target regions for ECS resource discovery
126
+ - SkipProfiles/SkipAccounts: Exclusion filters
127
+ - RootOnly: Limit to organization root accounts
128
+ - AccessRoles: IAM roles for cross-account access
129
+ - Filename: Output file for CSV export
130
+ - Time: Enable performance timing metrics
131
+ - loglevel: Logging verbosity configuration
132
+ - pStatus: Filter tasks by status (running/stopped)
133
+
134
+ Configuration Options:
135
+ - Multi-region scanning with region filters for targeted container analysis
136
+ - Multi-profile support for federated access across container platforms
137
+ - Extended arguments for advanced filtering and account selection
138
+ - Root-only mode for organization-level container inventory
139
+ - Role-based access for cross-account ECS resource discovery
140
+ - File output for integration with container management tools
141
+ - Timing metrics for performance optimization and monitoring
142
+ - Status filtering for task state analysis (running, stopped, or both)
143
+ - Verbose logging for debugging and container platform audit
144
+
145
+ ECS-Specific Features:
146
+ - Task status filtering to focus on specific workload states
147
+ - Support for container lifecycle analysis and monitoring
148
+ - Integration with enterprise container governance workflows
149
+ """
150
+ script_path, script_name = split(sys.argv[0])
151
+ parser = CommonArguments()
152
+ parser.my_parser.description = "Discover and analyze ECS clusters, services, and tasks across multiple AWS accounts and regions for enterprise container platform management."
153
+ parser.multiprofile()
154
+ parser.multiregion()
155
+ parser.extendedargs()
156
+ parser.rolestouse()
157
+ parser.rootOnly()
158
+ parser.save_to_file()
159
+ parser.timing()
160
+ parser.verbosity()
161
+ parser.version(__version__)
162
+ local = parser.my_parser.add_argument_group(script_name, "Parameters specific to this script")
163
+ local.add_argument(
164
+ "-s",
165
+ "--status",
166
+ dest="pStatus",
167
+ choices=["running", "stopped"],
168
+ type=str,
169
+ default=None,
170
+ help="Filter ECS tasks by status: 'running' for active workloads, 'stopped' for terminated tasks, or omit for both states",
171
+ )
172
+ return parser.my_parser.parse_args(f_arguments)
173
+
174
+
175
+ # The parameters passed to this function should be the dictionary of attributes that will be examined within the thread.
176
+ def find_all_clusters_and_tasks(fAllCredentials: list, fStatus: str = None) -> list:
177
+ """
178
+ Discover and inventory ECS clusters, services, and tasks across multiple AWS accounts and regions.
179
+
180
+ Performs comprehensive ECS resource discovery using multi-threaded processing to efficiently
181
+ inventory containerized workloads across enterprise AWS environments. Supports status filtering
182
+ for task lifecycle analysis and provides detailed metadata for capacity planning and governance.
183
+
184
+ Args:
185
+ fAllCredentials (list): List of credential dictionaries for cross-account access containing:
186
+ - AccountId: AWS account number
187
+ - Region: Target AWS region
188
+ - Success: Boolean indicating credential validity
189
+ - MgmtAccount: Management account identifier
190
+ - ParentProfile: Source AWS profile
191
+ fStatus (str, optional): Filter tasks by status ('running', 'stopped', or None for all)
192
+
193
+ Returns:
194
+ list: Comprehensive list of ECS resource dictionaries containing:
195
+ - MgmtAccount: Management account identifier for organizational hierarchy
196
+ - AccountId: AWS account containing the ECS resources
197
+ - Region: AWS region where resources are located
198
+ - ClusterName: ECS cluster identifier
199
+ - ServiceName: ECS service name (if applicable)
200
+ - TaskDefinition: Task definition ARN and revision
201
+ - TaskArn: Unique task identifier
202
+ - TaskStatus: Current task state (RUNNING, STOPPED, PENDING)
203
+ - ContainerInstances: EC2 instances hosting containers
204
+ - ParentProfile: Source profile for audit and governance
205
+ - LaunchType: Container launch type (EC2, FARGATE)
206
+ - PlatformVersion: ECS platform version for Fargate tasks
207
+
208
+ Threading Architecture:
209
+ - Worker thread pool with maximum 25 concurrent threads for scalability
210
+ - Queue-based task distribution for efficient resource discovery
211
+ - Thread-safe error handling and progress tracking with tqdm
212
+ - Graceful degradation for account access failures and authorization issues
213
+
214
+ Enterprise Features:
215
+ - Cross-account ECS resource discovery with assume role capabilities
216
+ - Container workload analysis with status filtering for lifecycle management
217
+ - Progress tracking for operational visibility during large-scale operations
218
+ - Comprehensive error handling for authorization and throttling scenarios
219
+
220
+ Error Handling:
221
+ - Authorization failure detection with region opt-in diagnostics
222
+ - AWS API throttling management with appropriate logging
223
+ - Graceful handling of missing resources and empty responses
224
+ - Thread-safe error reporting and progress updates
225
+
226
+ Performance Considerations:
227
+ - Configurable thread pool size based on credential set size
228
+ - Efficient memory management for large container inventories
229
+ - Progress tracking with real-time feedback for long operations
230
+ - Optimized data structures for enterprise-scale resource discovery
231
+ """
232
+
233
+ # Worker thread class for concurrent ECS resource discovery
234
+ class FindInstances(Thread):
235
+ def __init__(self, queue):
236
+ Thread.__init__(self)
237
+ self.queue = queue
238
+
239
+ def run(self):
240
+ """
241
+ Main worker thread execution loop for ECS resource discovery and analysis.
242
+
243
+ Continuously processes credential sets from the shared work queue, performing
244
+ comprehensive ECS cluster, service, and task discovery operations with detailed
245
+ metadata extraction and enterprise container platform analysis.
246
+ """
247
+ while True:
248
+ # Retrieve ECS discovery work item from thread-safe queue
249
+ c_account_credentials = self.queue.get()
250
+ logging.info(f"De-queued info for account number {c_account_credentials['AccountId']}")
251
+
252
+ try:
253
+ # Execute comprehensive ECS resource discovery for the current account/region
254
+ # This calls the inventory module's specialized ECS discovery function
255
+ EcsInfo = Inventory_Modules.find_account_ecs_clusters_services_and_tasks2(c_account_credentials)
256
+ logging.info(
257
+ f"Account: {c_account_credentials['AccountId']} Region: {c_account_credentials['Region']} | Discovered ECS resources"
258
+ )
259
+
260
+ # Initialize ECS resource metadata variables with defaults
261
+ ClusterName = ServiceName = TaskDefinition = TaskArn = TaskStatus = ""
262
+ LaunchType = PlatformVersion = ContainerInstanceArn = ""
263
+
264
+ # Process discovered ECS clusters, services, and tasks with comprehensive metadata extraction
265
+ # ECS resources have a hierarchical structure: Clusters -> Services -> Tasks
266
+ if "Clusters" in EcsInfo and EcsInfo["Clusters"]:
267
+ for cluster in EcsInfo["Clusters"]:
268
+ ClusterName = cluster.get("clusterName", "Unknown")
269
+ ClusterArn = cluster.get("clusterArn", "")
270
+ ClusterStatus = cluster.get("status", "")
271
+
272
+ # Process ECS services within each cluster for workload analysis
273
+ if "Services" in cluster and cluster["Services"]:
274
+ for service in cluster["Services"]:
275
+ ServiceName = service.get("serviceName", "Unknown")
276
+ ServiceArn = service.get("serviceArn", "")
277
+ ServiceStatus = service.get("status", "")
278
+ TaskDefinition = service.get("taskDefinition", "")
279
+
280
+ # Extract running task count for capacity analysis
281
+ RunningCount = service.get("runningCount", 0)
282
+ PendingCount = service.get("pendingCount", 0)
283
+ DesiredCount = service.get("desiredCount", 0)
284
+
285
+ # Process ECS tasks for detailed workload state analysis
286
+ if "Tasks" in service and service["Tasks"]:
287
+ for task in service["Tasks"]:
288
+ TaskArn = task.get("taskArn", "")
289
+ TaskStatus = task.get("lastStatus", "")
290
+ LaunchType = task.get("launchType", "")
291
+ PlatformVersion = task.get("platformVersion", "")
292
+
293
+ # Extract container instance information for EC2 launch type
294
+ ContainerInstanceArn = task.get("containerInstanceArn", "")
295
+
296
+ # Apply status filtering for task lifecycle analysis
297
+ if fStatus is None or fStatus.upper() == TaskStatus.upper():
298
+ # Create comprehensive ECS resource record for enterprise inventory
299
+ ecs_record = {
300
+ # Organizational context for multi-account container management
301
+ "MgmtAccount": c_account_credentials["MgmtAccount"],
302
+ "AccountId": c_account_credentials["AccountId"],
303
+ "Region": c_account_credentials["Region"],
304
+ "ParentProfile": c_account_credentials["ParentProfile"],
305
+ # ECS cluster hierarchy and identification
306
+ "ClusterName": ClusterName,
307
+ "ClusterArn": ClusterArn,
308
+ "ClusterStatus": ClusterStatus,
309
+ # ECS service configuration and capacity
310
+ "ServiceName": ServiceName,
311
+ "ServiceArn": ServiceArn,
312
+ "ServiceStatus": ServiceStatus,
313
+ "TaskDefinition": TaskDefinition,
314
+ # Service capacity metrics for planning
315
+ "RunningCount": RunningCount,
316
+ "PendingCount": PendingCount,
317
+ "DesiredCount": DesiredCount,
318
+ # Task-level metadata and runtime information
319
+ "TaskArn": TaskArn,
320
+ "TaskStatus": TaskStatus,
321
+ "LaunchType": LaunchType,
322
+ "PlatformVersion": PlatformVersion,
323
+ "ContainerInstanceArn": ContainerInstanceArn,
324
+ }
325
+
326
+ # Add to enterprise container platform inventory
327
+ AllInstances.append(ecs_record)
328
+ else:
329
+ # Skip tasks that don't match status filter
330
+ continue
331
+ else:
332
+ # Handle services without tasks (potentially new or scaled-down services)
333
+ if fStatus is None: # Only include in comprehensive inventory mode
334
+ service_record = {
335
+ # Organizational context
336
+ "MgmtAccount": c_account_credentials["MgmtAccount"],
337
+ "AccountId": c_account_credentials["AccountId"],
338
+ "Region": c_account_credentials["Region"],
339
+ "ParentProfile": c_account_credentials["ParentProfile"],
340
+ # Service-level information without tasks
341
+ "ClusterName": ClusterName,
342
+ "ServiceName": ServiceName,
343
+ "ServiceStatus": ServiceStatus,
344
+ "TaskDefinition": TaskDefinition,
345
+ "RunningCount": RunningCount,
346
+ "PendingCount": PendingCount,
347
+ "DesiredCount": DesiredCount,
348
+ # Empty task fields for consistency
349
+ "TaskArn": "",
350
+ "TaskStatus": "NO_TASKS",
351
+ "LaunchType": "",
352
+ "PlatformVersion": "",
353
+ "ContainerInstanceArn": "",
354
+ }
355
+ AllInstances.append(service_record)
356
+ else:
357
+ # Handle clusters without services (empty or infrastructure-only clusters)
358
+ if fStatus is None: # Only include in comprehensive inventory mode
359
+ cluster_record = {
360
+ # Organizational context
361
+ "MgmtAccount": c_account_credentials["MgmtAccount"],
362
+ "AccountId": c_account_credentials["AccountId"],
363
+ "Region": c_account_credentials["Region"],
364
+ "ParentProfile": c_account_credentials["ParentProfile"],
365
+ # Cluster-only information
366
+ "ClusterName": ClusterName,
367
+ "ClusterStatus": ClusterStatus,
368
+ # Empty service and task fields for consistency
369
+ "ServiceName": "NO_SERVICES",
370
+ "ServiceStatus": "",
371
+ "TaskDefinition": "",
372
+ "RunningCount": 0,
373
+ "PendingCount": 0,
374
+ "DesiredCount": 0,
375
+ "TaskArn": "",
376
+ "TaskStatus": "",
377
+ "LaunchType": "",
378
+ "PlatformVersion": "",
379
+ "ContainerInstanceArn": "",
380
+ }
381
+ AllInstances.append(cluster_record)
382
+ except KeyError as my_Error:
383
+ # Handle cases where expected keys are missing from ECS API responses
384
+ logging.error(f"Account Access failed - trying to access {c_account_credentials['AccountId']}")
385
+ logging.info(f"Actual Error: {my_Error}")
386
+ pass
387
+ except AttributeError as my_Error:
388
+ # Handle cases where profile configuration is incorrect
389
+ logging.error(f"Error: Likely that one of the supplied profiles was wrong")
390
+ logging.warning(my_Error)
391
+ continue
392
+ except ClientError as my_Error:
393
+ # Handle AWS API errors including authorization failures and throttling
394
+ if "AuthFailure" in str(my_Error):
395
+ logging.error(
396
+ f"Authorization Failure accessing account {c_account_credentials['AccountId']} in {c_account_credentials['Region']} region"
397
+ )
398
+ logging.warning(
399
+ f"It's possible that the region {c_account_credentials['Region']} hasn't been opted-into"
400
+ )
401
+ continue
402
+ else:
403
+ # Handle API throttling and service limits for ECS operations
404
+ logging.error(f"Error: Likely throttling errors from too much ECS API activity")
405
+ logging.warning(my_Error)
406
+ continue
407
+ finally:
408
+ # Ensure progress tracking and queue management regardless of success/failure
409
+ pbar.update()
410
+ self.queue.task_done()
411
+
412
+ ###########
413
+ # Initialize queue-based threading architecture for scalable ECS resource discovery
414
+ ###########
415
+
416
+ # Create thread-safe queue for distributing work across worker threads
417
+ checkqueue = Queue()
418
+
419
+ # Initialize results list for aggregating discovered ECS resources
420
+ AllInstances = []
421
+
422
+ # Configure worker thread pool size - balance between performance and AWS API limits
423
+ # Maximum 25 threads to prevent overwhelming AWS APIs while maintaining efficiency
424
+ WorkerThreads = min(len(fAllCredentials), 25)
425
+
426
+ # Initialize progress tracking for operational visibility during large-scale operations
427
+ pbar = tqdm(
428
+ desc=f"Finding ECS clusters, services and tasks from {len(fAllCredentials)} accounts / regions",
429
+ total=len(fAllCredentials),
430
+ unit=" locations",
431
+ )
432
+
433
+ # Start worker threads for concurrent ECS resource discovery
434
+ for x in range(WorkerThreads):
435
+ worker = FindInstances(checkqueue)
436
+ # Setting daemon to True allows main thread exit even if workers are still processing
437
+ worker.daemon = True
438
+ worker.start()
439
+
440
+ # Queue credential sets for processing by worker threads
441
+ for credential in fAllCredentials:
442
+ logging.info(f"Beginning to queue data - starting with {credential['AccountId']}")
443
+ try:
444
+ # Queue individual credential set for ECS resource discovery
445
+ # Note: Single parameter queuing - credential dictionary contains all needed info
446
+ checkqueue.put(credential)
447
+ except ClientError as my_Error:
448
+ # Handle authorization failures during credential queuing
449
+ if "AuthFailure" in str(my_Error):
450
+ logging.error(
451
+ f"Authorization Failure accessing account {credential['AccountId']} in {credential['Region']} region"
452
+ )
453
+ logging.warning(f"It's possible that the region {credential['Region']} hasn't been opted-into")
454
+ pass
455
+
456
+ # Wait for all queued work to complete before proceeding
457
+ checkqueue.join()
458
+ pbar.close()
459
+ return AllInstances
460
+
461
+
462
+ ##################
463
+ # Main execution entry point for enterprise ECS resource discovery and analysis
464
+ ##################
465
+
466
+ if __name__ == "__main__":
467
+ """
468
+ Main orchestration for comprehensive ECS cluster, service, and task discovery operations.
469
+
470
+ Coordinates multi-account, multi-region ECS resource inventory with detailed container
471
+ platform analysis, capacity planning support, and enterprise containerized workload
472
+ governance across AWS Organizations environments.
473
+ """
474
+ # Parse enterprise command-line arguments with ECS-specific container platform options
475
+ args = parse_args(sys.argv[1:])
476
+
477
+ # Extract configuration parameters for multi-account container platform discovery
478
+ pProfiles = args.Profiles # AWS profile list for federated ECS access
479
+ pRegionList = args.Regions # Target regions for ECS cluster enumeration
480
+ pAccounts = args.Accounts # Specific account targeting for focused container analysis
481
+ pSkipAccounts = args.SkipAccounts # Account exclusion list for organizational policy compliance
482
+ pSkipProfiles = args.SkipProfiles # Profile exclusion for credential optimization
483
+ pAccessRoles = args.AccessRoles # Cross-account roles for Organizations ECS access
484
+ pStatus = args.pStatus # Task status filter for container lifecycle analysis
485
+ pRootOnly = args.RootOnly # Organization root account limitation flag
486
+ pFilename = args.Filename # CSV export file for enterprise container reporting
487
+ pTiming = args.Time # Performance timing for operational optimization
488
+ verbose = args.loglevel # Logging verbosity for container platform visibility
489
+
490
+ # Configure enterprise logging infrastructure for ECS operations audit trail
491
+ logging.basicConfig(level=verbose, format="[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s")
492
+ logging.getLogger("boto3").setLevel(logging.CRITICAL)
493
+ logging.getLogger("botocore").setLevel(logging.CRITICAL)
494
+ logging.getLogger("s3transfer").setLevel(logging.CRITICAL)
495
+ logging.getLogger("urllib3").setLevel(logging.CRITICAL)
496
+
497
+ print()
498
+ print(f"Checking for ECS clusters, services, and tasks... ")
499
+ print()
500
+
501
+ # Execute enterprise credential discovery and validation across organizational container infrastructure
502
+ CredentialList = get_all_credentials(
503
+ pProfiles, pTiming, pSkipProfiles, pSkipAccounts, pRootOnly, pAccounts, pRegionList, pAccessRoles
504
+ )
505
+
506
+ # Calculate organizational scope for executive container platform reporting
507
+ AccountNum = len(set([acct["AccountId"] for acct in CredentialList]))
508
+ RegionNum = len(set([acct["Region"] for acct in CredentialList]))
509
+ print()
510
+ print(f"Searching total of {AccountNum} accounts and {RegionNum} regions for ECS resources")
511
+
512
+ # Display performance timing for credential discovery phase optimization
513
+ if pTiming:
514
+ print()
515
+ milestone_time1 = time()
516
+ print(
517
+ f"{Fore.GREEN}\t\tCredential discovery and region enumeration took: {(milestone_time1 - begin_time):.3f} seconds{Fore.RESET}"
518
+ )
519
+ print()
520
+
521
+ print(f"Now running through all accounts and regions to discover ECS resources...")
522
+
523
+ # Execute comprehensive multi-threaded ECS resource discovery and container platform analysis
524
+ AllInstances = find_all_clusters_and_tasks(CredentialList, pStatus)
525
+
526
+ # Configure enterprise ECS resource inventory report display formatting
527
+ display_dict = {
528
+ "ParentProfile": {"DisplayOrder": 1, "Heading": "Parent Profile"}, # Source profile for audit
529
+ "MgmtAccount": {"DisplayOrder": 2, "Heading": "Mgmt Acct"}, # Management account hierarchy
530
+ "AccountId": {"DisplayOrder": 3, "Heading": "Acct Number"}, # Account identifier
531
+ "Region": {"DisplayOrder": 4, "Heading": "Region"}, # AWS region
532
+ "ClusterName": {"DisplayOrder": 5, "Heading": "Cluster"}, # ECS cluster name
533
+ "ServiceName": {"DisplayOrder": 6, "Heading": "Service"}, # ECS service name
534
+ "TaskStatus": {"DisplayOrder": 7, "Heading": "Task Status"}, # Task lifecycle state
535
+ "LaunchType": {"DisplayOrder": 8, "Heading": "Launch Type"}, # EC2 or Fargate
536
+ "RunningCount": {"DisplayOrder": 9, "Heading": "Running Tasks"}, # Active task count
537
+ "DesiredCount": {"DisplayOrder": 10, "Heading": "Desired Tasks"}, # Target task count
538
+ }
539
+
540
+ # Sort ECS resources for consistent enterprise reporting and operational visibility
541
+ sorted_all_instances = sorted(
542
+ AllInstances,
543
+ key=lambda d: (d["ParentProfile"], d["MgmtAccount"], d["Region"], d["AccountId"], d.get("ClusterName", "")),
544
+ )
545
+
546
+ # Generate comprehensive ECS resource inventory report with CSV export capability
547
+ display_results(sorted_all_instances, display_dict, None, pFilename)
548
+
549
+ # Display performance timing metrics for operational optimization and SLA compliance
550
+ if pTiming:
551
+ print(ERASE_LINE)
552
+ print(f"{Fore.GREEN}This script took {time() - begin_time:.2f} seconds{Fore.RESET}")
553
+
554
+ print(ERASE_LINE)
555
+
556
+ # Display comprehensive operational summary for executive container platform reporting
557
+ print(f"Found {len(AllInstances)} ECS resources across {AccountNum} accounts across {RegionNum} regions")
558
+ print()
559
+
560
+ # Display completion message for user confirmation and operational closure
561
+ print("Thank you for using this script")
562
+ print()