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,411 @@
1
+ #!/usr/bin/env python3
2
+
3
+ """
4
+ AWS Elastic Load Balancers Discovery and Analysis Script
5
+
6
+ This script provides comprehensive discovery and inventory capabilities for AWS Elastic
7
+ Load Balancers (ELBs) across multiple accounts and regions. It's designed for enterprise
8
+ infrastructure teams who need visibility into load balancer distribution, capacity
9
+ planning, and traffic management across large-scale AWS deployments.
10
+
11
+ Key Features:
12
+ - Multi-account ELB discovery using assume role capabilities
13
+ - Multi-region scanning with configurable region targeting
14
+ - Load balancer metadata extraction including state and DNS information
15
+ - Status filtering for active and inactive load balancer analysis
16
+ - Fragment-based search for targeted load balancer discovery
17
+ - Enterprise reporting with structured output and integration capabilities
18
+ - Profile-based authentication with support for federated access
19
+
20
+ Enterprise Use Cases:
21
+ - Load balancer inventory and governance across organizations
22
+ - Traffic distribution analysis for performance optimization
23
+ - Capacity planning for application load balancing infrastructure
24
+ - Compliance reporting for load balancer security and configuration standards
25
+ - Multi-account traffic management visibility and coordination
26
+ - Disaster recovery planning with load balancer distribution analysis
27
+ - Cost optimization through load balancer utilization tracking
28
+
29
+ Load Balancing Infrastructure Features:
30
+ - Classic Load Balancer (ELB) enumeration with health status
31
+ - Application Load Balancer (ALB) discovery and configuration analysis
32
+ - Network Load Balancer (NLB) inventory with performance metrics
33
+ - Load balancer state tracking (active, provisioning, failed)
34
+ - DNS name resolution and endpoint management
35
+ - Target group and backend instance analysis
36
+
37
+ Security Considerations:
38
+ - Uses IAM assume role capabilities for cross-account ELB access
39
+ - Implements proper error handling for authorization failures
40
+ - Supports read-only operations with no load balancer modification capabilities
41
+ - Respects ELB service permissions and regional access constraints
42
+ - Provides comprehensive audit trail through detailed logging
43
+
44
+ Load Balancer Analysis:
45
+ - State monitoring for operational health assessment
46
+ - DNS configuration validation for service endpoint management
47
+ - Performance characteristics analysis for optimization
48
+ - Security group and network access control evaluation
49
+ - SSL/TLS certificate management and compliance tracking
50
+
51
+ Performance Considerations:
52
+ - Multi-threaded processing for concurrent ELB API operations
53
+ - Progress tracking with tqdm for operational visibility during long operations
54
+ - Efficient credential management for cross-account load balancer access
55
+ - Memory-optimized data structures for large load balancer inventories
56
+ - Queue-based worker architecture for scalable discovery operations
57
+
58
+ Threading Architecture:
59
+ - Worker thread pool with configurable concurrency (max 10 threads for ELB APIs)
60
+ - Queue-based task distribution for efficient resource discovery
61
+ - Thread-safe error handling and progress tracking
62
+ - Graceful degradation for account access failures
63
+
64
+ Dependencies:
65
+ - boto3/botocore for AWS ELB API interactions
66
+ - Inventory_Modules for common utility functions and credential management
67
+ - ArgumentsClass for standardized CLI argument parsing
68
+ - threading and queue for concurrent processing architecture
69
+ - colorama for enhanced output formatting and tqdm for progress tracking
70
+
71
+ Future Enhancements:
72
+ - Application Load Balancer (ALB) target group analysis
73
+ - Network Load Balancer (NLB) performance metrics integration
74
+ - SSL certificate expiration monitoring and alerting
75
+ - Load balancer security configuration compliance checking
76
+ - Cost optimization recommendations based on traffic patterns
77
+
78
+ Author: AWS CloudOps Team
79
+ Version: 2024.05.06
80
+ """
81
+
82
+ import logging
83
+ import sys
84
+ from os.path import split
85
+ from queue import Queue
86
+ from threading import Thread
87
+ from time import time
88
+
89
+ from ArgumentsClass import CommonArguments
90
+ from botocore.exceptions import ClientError
91
+ from colorama import Fore, init
92
+ from Inventory_Modules import display_results, find_load_balancers2, get_all_credentials
93
+ from tqdm.auto import tqdm
94
+
95
+ init()
96
+ __version__ = "2024.05.06"
97
+ ERASE_LINE = "\x1b[2K"
98
+ begin_time = time()
99
+
100
+
101
+ ##################
102
+ # Functions
103
+ ##################
104
+
105
+
106
+ def parse_args(arguments):
107
+ """
108
+ Parse command line arguments for AWS Elastic Load Balancer discovery operations.
109
+
110
+ Configures comprehensive argument parsing for multi-account, multi-region ELB
111
+ inventory operations. Supports enterprise load balancing infrastructure management
112
+ with profile management, region targeting, organizational access controls, status
113
+ filtering, and fragment-based search for targeted discovery operations.
114
+
115
+ Args:
116
+ arguments (list): Command line arguments from sys.argv[1:]
117
+
118
+ Returns:
119
+ argparse.Namespace: Parsed arguments containing:
120
+ - Profiles: List of AWS profiles to process
121
+ - Regions: Target regions for ELB discovery
122
+ - SkipProfiles/SkipAccounts: Exclusion filters
123
+ - RootOnly: Limit to organization root accounts
124
+ - AccessRoles: IAM roles for cross-account access
125
+ - Fragments: Name fragments for targeted ELB search
126
+ - pstatus: Load balancer status filter
127
+ - Time: Enable performance timing metrics
128
+ - loglevel: Logging verbosity configuration
129
+
130
+ Configuration Options:
131
+ - Multi-region scanning with region filters for targeted load balancer analysis
132
+ - Multi-profile support for federated access across load balancing infrastructure
133
+ - Extended arguments for advanced filtering and account selection
134
+ - Root-only mode for organization-level load balancer inventory
135
+ - Role-based access for cross-account ELB resource discovery
136
+ - Fragment search for finding specific load balancers by name patterns
137
+ - Status filtering for operational state analysis and monitoring
138
+ - Timing metrics for performance optimization and monitoring
139
+ - Verbose logging for debugging and infrastructure audit
140
+
141
+ ELB-Specific Features:
142
+ - Load balancer status filtering to focus on operational states
143
+ - Fragment-based search for targeted load balancer discovery
144
+ - Support for traffic management analysis and monitoring
145
+ - Integration with enterprise load balancing governance workflows
146
+ """
147
+ script_path, script_name = split(sys.argv[0])
148
+ parser = CommonArguments()
149
+ parser.my_parser.description = "Discover and analyze AWS Elastic Load Balancers across multiple accounts and regions for enterprise traffic management and infrastructure planning."
150
+ parser.multiprofile()
151
+ parser.multiregion()
152
+ parser.extendedargs()
153
+ parser.rootOnly()
154
+ parser.rolestouse()
155
+ parser.fragment()
156
+ parser.verbosity()
157
+ parser.timing()
158
+ parser.version(__version__)
159
+ local = parser.my_parser.add_argument_group(script_name, "Parameters specific to this script")
160
+ local.add_argument(
161
+ "-s",
162
+ "--status",
163
+ dest="pstatus",
164
+ metavar="Load balancer status",
165
+ default="active",
166
+ help="Filter load balancers by operational status: 'active' for operational ELBs, 'provisioning' for pending, 'failed' for error states",
167
+ )
168
+ return parser.my_parser.parse_args(arguments)
169
+
170
+
171
+ def find_all_elbs(fAllCredentials: list, ffragment: list, fstatus: str):
172
+ """
173
+ Discover and inventory AWS Elastic Load Balancers across multiple accounts and regions.
174
+
175
+ Performs comprehensive ELB discovery using multi-threaded processing to efficiently
176
+ inventory load balancing infrastructure across enterprise AWS environments. Supports
177
+ fragment-based filtering for targeted discovery and status filtering for operational
178
+ state analysis and traffic management planning.
179
+
180
+ Args:
181
+ fAllCredentials (list): List of credential dictionaries for cross-account access containing:
182
+ - AccountId: AWS account number
183
+ - Region: Target AWS region
184
+ - Success: Boolean indicating credential validity
185
+ - MgmtAccount: Management account identifier
186
+ - ParentProfile: Source AWS profile
187
+ ffragment (list): Name fragments for targeted load balancer search and filtering
188
+ fstatus (str): Load balancer status filter ('active', 'provisioning', 'failed', etc.)
189
+
190
+ Returns:
191
+ list: Comprehensive list of load balancer dictionaries containing:
192
+ - MgmtAccount: Management account identifier for organizational hierarchy
193
+ - AccountId: AWS account containing the load balancer
194
+ - Region: AWS region where load balancer is located
195
+ - Name: Load balancer name identifier
196
+ - Status: Current operational state (active, provisioning, failed)
197
+ - DNSName: Load balancer DNS endpoint for traffic routing
198
+
199
+ Threading Architecture:
200
+ - Worker thread pool with maximum 10 concurrent threads for ELB API optimization
201
+ - Queue-based task distribution for efficient load balancer discovery
202
+ - Thread-safe error handling and progress tracking
203
+ - Graceful degradation for account access failures and authorization issues
204
+
205
+ Enterprise Features:
206
+ - Cross-account load balancer discovery with assume role capabilities
207
+ - Fragment-based search for targeted load balancer identification
208
+ - Status filtering for operational state monitoring and analysis
209
+ - Comprehensive error handling for authorization and throttling scenarios
210
+
211
+ Error Handling:
212
+ - Authorization failure detection with region opt-in diagnostics
213
+ - AWS API throttling management with appropriate logging
214
+ - Graceful handling of missing load balancers and empty responses
215
+ - Thread-safe error reporting and progress updates
216
+
217
+ Performance Considerations:
218
+ - Optimized thread pool size for ELB API rate limits
219
+ - Efficient memory management for large load balancer inventories
220
+ - Progress tracking for operational visibility during discovery
221
+ - Load balancer metadata extraction for enterprise reporting
222
+ """
223
+
224
+ # Worker thread class for concurrent load balancer discovery
225
+ class FindLoadBalancers(Thread):
226
+ def __init__(self, queue):
227
+ Thread.__init__(self)
228
+ self.queue = queue
229
+
230
+ def run(self):
231
+ while True:
232
+ # Get the work from the queue and expand the tuple
233
+ c_account_credentials, c_fragment, c_status = self.queue.get()
234
+ logging.info(f"De-queued info for account number {c_account_credentials['AccountId']}")
235
+ try:
236
+ # Discover load balancers using inventory module with fragment and status filtering
237
+ LoadBalancers = find_load_balancers2(c_account_credentials, c_fragment, c_status)
238
+ logging.info(
239
+ f"Account: {c_account_credentials['AccountId']} Region: {c_account_credentials['Region']} | Found {len(LoadBalancers)} load balancers"
240
+ )
241
+
242
+ # Process each discovered load balancer and extract enterprise metadata
243
+ for lb in LoadBalancers:
244
+ All_Load_Balancers.append(
245
+ {
246
+ # Management account for organizational hierarchy tracking
247
+ "MgmtAccount": c_account_credentials["MgmtAccount"],
248
+ # Account containing the load balancer for governance
249
+ "AccountId": c_account_credentials["AccountId"],
250
+ # Regional placement for capacity planning and disaster recovery
251
+ "Region": c_account_credentials["Region"],
252
+ # Load balancer name for identification and management
253
+ "Name": lb["LoadBalancerName"],
254
+ # Operational status for health monitoring
255
+ "Status": lb["State"]["Code"],
256
+ # DNS endpoint for traffic routing configuration
257
+ "DNSName": lb["DNSName"],
258
+ }
259
+ )
260
+ except KeyError as my_Error:
261
+ logging.error(f"Account Access failed - trying to access {c_account_credentials['AccountId']}")
262
+ logging.info(f"Actual Error: {my_Error}")
263
+ pass
264
+ except AttributeError as my_Error:
265
+ logging.error(f"Error: Likely that one of the supplied profiles was wrong")
266
+ logging.warning(my_Error)
267
+ continue
268
+ except ClientError as my_Error:
269
+ # Handle AWS API errors including authorization failures and throttling
270
+ if "AuthFailure" in str(my_Error):
271
+ logging.error(
272
+ f"Authorization Failure accessing account {c_account_credentials['AccountId']} in {c_account_credentials['Region']} region"
273
+ )
274
+ logging.warning(
275
+ f"It's possible that the region {c_account_credentials['Region']} hasn't been opted-into"
276
+ )
277
+ continue
278
+ else:
279
+ # Handle throttling and other AWS API errors
280
+ logging.error(f"Error: Likely throttling errors from too much activity")
281
+ logging.warning(my_Error)
282
+ continue
283
+ finally:
284
+ # Ensure queue management regardless of success/failure
285
+ self.queue.task_done()
286
+
287
+ ###########
288
+ # Initialize queue-based threading architecture for scalable load balancer discovery
289
+ ###########
290
+
291
+ # Create thread-safe queue for distributing work across worker threads
292
+ checkqueue = Queue()
293
+
294
+ # Initialize results list for aggregating discovered load balancers
295
+ All_Load_Balancers = []
296
+
297
+ # Configure worker thread pool size optimized for ELB API rate limits
298
+ # Maximum 10 threads to prevent overwhelming ELB APIs while maintaining efficiency
299
+ WorkerThreads = min(len(fAllCredentials), 10)
300
+
301
+ # Start worker threads for concurrent load balancer discovery
302
+ for x in range(WorkerThreads):
303
+ worker = FindLoadBalancers(checkqueue)
304
+ # Setting daemon to True allows main thread exit even if workers are still processing
305
+ worker.daemon = True
306
+ worker.start()
307
+
308
+ # Queue credential sets with progress tracking for operational visibility
309
+ for credential in tqdm(fAllCredentials):
310
+ logging.info(f"Beginning to queue data - starting with {credential['AccountId']}")
311
+ try:
312
+ # Queue credential set with fragment and status filters for targeted discovery
313
+ # Tuple format: (credentials, fragment_filter, status_filter)
314
+ checkqueue.put((credential, ffragment, fstatus))
315
+ except ClientError as my_Error:
316
+ # Handle authorization failures during credential queuing
317
+ if "AuthFailure" in str(my_Error):
318
+ logging.error(
319
+ f"Authorization Failure accessing account {credential['AccountId']} in {credential['Region']} region"
320
+ )
321
+ logging.warning(f"It's possible that the region {credential['Region']} hasn't been opted-into")
322
+ pass
323
+
324
+ # Wait for all queued work to complete before proceeding
325
+ checkqueue.join()
326
+ return All_Load_Balancers
327
+
328
+
329
+ ##################
330
+ # Main execution entry point for enterprise load balancer discovery and traffic management analysis
331
+ ##################
332
+
333
+ if __name__ == "__main__":
334
+ """
335
+ Main orchestration for comprehensive AWS Elastic Load Balancer discovery and analysis.
336
+
337
+ Coordinates multi-account, multi-region load balancer inventory with detailed traffic
338
+ management analysis, capacity planning support, and enterprise load balancing
339
+ infrastructure governance across AWS Organizations environments.
340
+ """
341
+ # Parse enterprise command-line arguments with ELB-specific traffic management options
342
+ args = parse_args(sys.argv[1:])
343
+
344
+ # Extract configuration parameters for multi-account load balancer discovery
345
+ pProfiles = args.Profiles # AWS profile list for federated ELB access
346
+ pRegionList = args.Regions # Target regions for load balancer enumeration
347
+ pAccounts = args.Accounts # Specific account targeting for focused traffic analysis
348
+ pSkipAccounts = args.SkipAccounts # Account exclusion list for organizational policy compliance
349
+ pSkipProfiles = args.SkipProfiles # Profile exclusion for credential optimization
350
+ pAccessRoles = args.AccessRoles # Cross-account roles for Organizations ELB access
351
+ pFragment = args.Fragments # Name fragments for targeted load balancer discovery
352
+ pStatus = args.pstatus # Load balancer status filter for operational analysis
353
+ pRootOnly = args.RootOnly # Organization root account limitation flag
354
+ pTiming = args.Time # Performance timing for operational optimization
355
+ verbose = args.loglevel # Logging verbosity for load balancing infrastructure visibility
356
+
357
+ # Configure enterprise logging infrastructure for ELB operations audit trail
358
+ logging.basicConfig(level=verbose, format="[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s")
359
+ logging.getLogger("boto3").setLevel(logging.CRITICAL)
360
+ logging.getLogger("botocore").setLevel(logging.CRITICAL)
361
+ logging.getLogger("s3transfer").setLevel(logging.CRITICAL)
362
+ logging.getLogger("urllib3").setLevel(logging.CRITICAL)
363
+
364
+ # Configure enterprise ELB inventory report display formatting for traffic management analysis
365
+ display_dict = {
366
+ # 'ParentProfile': {'DisplayOrder': 1, 'Heading': 'Parent Profile'}, # Disabled for concise output
367
+ "MgmtAccount": {"DisplayOrder": 2, "Heading": "Mgmt Acct"}, # Management account hierarchy
368
+ "AccountId": {"DisplayOrder": 3, "Heading": "Acct Number"}, # Account identifier for governance
369
+ "Region": {"DisplayOrder": 4, "Heading": "Region"}, # AWS region for geographic distribution
370
+ "Name": {"DisplayOrder": 5, "Heading": "Name"}, # Load balancer name for identification
371
+ "Status": {"DisplayOrder": 6, "Heading": "Status"}, # Operational state for monitoring
372
+ "DNSName": {"DisplayOrder": 7, "Heading": "Public Name"}, # DNS endpoint for traffic routing
373
+ # 'State': {'DisplayOrder': 9, 'Heading': 'State', 'Condition': ['running']} # Reserved for future use
374
+ }
375
+
376
+ # Execute enterprise credential discovery and validation across organizational load balancing infrastructure
377
+ CredentialList = get_all_credentials(
378
+ pProfiles, pTiming, pSkipProfiles, pSkipAccounts, pRootOnly, pAccounts, pRegionList, pAccessRoles
379
+ )
380
+
381
+ # Calculate organizational scope for executive load balancing infrastructure reporting
382
+ AccountNum = len(set([acct["AccountId"] for acct in CredentialList]))
383
+ RegionNum = len(set([acct["Region"] for acct in CredentialList]))
384
+ WorkerThreads = min(AccountNum, 10) # Optimize thread pool for ELB API rate limits
385
+
386
+ print()
387
+ print(f"Looking through {RegionNum} regions and {AccountNum} accounts for load balancers")
388
+ print()
389
+
390
+ # Execute comprehensive multi-threaded ELB discovery with fragment and status filtering
391
+ All_Load_Balancers = find_all_elbs(CredentialList, pFragment, pStatus)
392
+
393
+ # Generate comprehensive load balancer inventory report with enterprise formatting
394
+ display_results(All_Load_Balancers, display_dict)
395
+
396
+ # Display performance timing metrics for operational optimization and SLA compliance
397
+ if pTiming:
398
+ print(ERASE_LINE)
399
+ print(f"{Fore.GREEN}This script took {time() - begin_time:.2f} seconds{Fore.RESET}")
400
+
401
+ print(ERASE_LINE)
402
+
403
+ # Display comprehensive operational summary for executive traffic management reporting
404
+ print(
405
+ f"{Fore.RED}Found {len(All_Load_Balancers)} Load Balancers across {AccountNum} profiles across {RegionNum} regions{Fore.RESET}"
406
+ )
407
+ print()
408
+
409
+ # Display completion message for user confirmation and operational closure
410
+ print("Thank you for using this script")
411
+ print()