multi-aws-tool 0.1.2__tar.gz → 0.2.0__tar.gz

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 (36) hide show
  1. multi_aws_tool-0.1.2/README.md → multi_aws_tool-0.2.0/PKG-INFO +85 -2
  2. multi_aws_tool-0.1.2/PKG-INFO → multi_aws_tool-0.2.0/README.md +62 -17
  3. {multi_aws_tool-0.1.2 → multi_aws_tool-0.2.0}/multi_aws_tool/__init__.py +8 -1
  4. {multi_aws_tool-0.1.2 → multi_aws_tool-0.2.0}/multi_aws_tool/aws/account_manager.py +195 -2
  5. multi_aws_tool-0.2.0/multi_aws_tool/aws/organizations_client.py +119 -0
  6. multi_aws_tool-0.2.0/multi_aws_tool/aws/profile_config.py +251 -0
  7. multi_aws_tool-0.2.0/multi_aws_tool/cli/commands.py +1910 -0
  8. multi_aws_tool-0.2.0/multi_aws_tool/cli/setup_wizard.py +203 -0
  9. multi_aws_tool-0.2.0/multi_aws_tool/config/template_manager.py +120 -0
  10. multi_aws_tool-0.2.0/multi_aws_tool/execution.py +263 -0
  11. multi_aws_tool-0.2.0/multi_aws_tool/mcp_server.py +526 -0
  12. {multi_aws_tool-0.1.2 → multi_aws_tool-0.2.0}/multi_aws_tool/models/account.py +11 -2
  13. multi_aws_tool-0.2.0/multi_aws_tool/models/template.py +71 -0
  14. {multi_aws_tool-0.1.2 → multi_aws_tool-0.2.0}/multi_aws_tool/output.py +37 -1
  15. multi_aws_tool-0.2.0/multi_aws_tool/services.py +917 -0
  16. multi_aws_tool-0.2.0/multi_aws_tool/tui/__init__.py +7 -0
  17. multi_aws_tool-0.2.0/multi_aws_tool/tui/app.py +2159 -0
  18. {multi_aws_tool-0.1.2 → multi_aws_tool-0.2.0}/multi_aws_tool/utils/validators.py +18 -1
  19. multi_aws_tool-0.2.0/pyproject.toml +39 -0
  20. multi_aws_tool-0.1.2/multi_aws_tool/cli/commands.py +0 -1832
  21. multi_aws_tool-0.1.2/pyproject.toml +0 -27
  22. {multi_aws_tool-0.1.2 → multi_aws_tool-0.2.0}/multi_aws_tool/aws/__init__.py +0 -0
  23. {multi_aws_tool-0.1.2 → multi_aws_tool-0.2.0}/multi_aws_tool/aws/sso_client.py +0 -0
  24. {multi_aws_tool-0.1.2 → multi_aws_tool-0.2.0}/multi_aws_tool/cli/__init__.py +0 -0
  25. {multi_aws_tool-0.1.2 → multi_aws_tool-0.2.0}/multi_aws_tool/config/__init__.py +0 -0
  26. {multi_aws_tool-0.1.2 → multi_aws_tool-0.2.0}/multi_aws_tool/config/manager.py +0 -0
  27. {multi_aws_tool-0.1.2 → multi_aws_tool-0.2.0}/multi_aws_tool/config/schema.py +0 -0
  28. {multi_aws_tool-0.1.2 → multi_aws_tool-0.2.0}/multi_aws_tool/main.py +0 -0
  29. {multi_aws_tool-0.1.2 → multi_aws_tool-0.2.0}/multi_aws_tool/models/__init__.py +0 -0
  30. {multi_aws_tool-0.1.2 → multi_aws_tool-0.2.0}/multi_aws_tool/models/config.py +0 -0
  31. {multi_aws_tool-0.1.2 → multi_aws_tool-0.2.0}/multi_aws_tool/models/result.py +0 -0
  32. {multi_aws_tool-0.1.2 → multi_aws_tool-0.2.0}/multi_aws_tool/utils/__init__.py +0 -0
  33. {multi_aws_tool-0.1.2 → multi_aws_tool-0.2.0}/multi_aws_tool/utils/account_data.py +0 -0
  34. {multi_aws_tool-0.1.2 → multi_aws_tool-0.2.0}/multi_aws_tool/utils/data_validation.py +0 -0
  35. {multi_aws_tool-0.1.2 → multi_aws_tool-0.2.0}/multi_aws_tool/utils/logging_config.py +0 -0
  36. {multi_aws_tool-0.1.2 → multi_aws_tool-0.2.0}/multi_aws_tool/utils/report_parser.py +0 -0
@@ -1,3 +1,26 @@
1
+ Metadata-Version: 2.4
2
+ Name: multi-aws-tool
3
+ Version: 0.2.0
4
+ Summary: Multi AWS tool for managing operations across multiple AWS accounts via SSO
5
+ Requires-Python: >=3.11
6
+ Description-Content-Type: text/markdown
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3 :: Only
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Classifier: Programming Language :: Python :: 3.14
13
+ Requires-Dist: click>=8.2
14
+ Requires-Dist: boto3>=1.40
15
+ Requires-Dist: pyyaml>=6.0.2
16
+ Requires-Dist: colorama>=0.4.6
17
+ Requires-Dist: tabulate>=0.9.0
18
+ Requires-Dist: mcp>=2.0,<3
19
+ Requires-Dist: pytest>=8 ; extra == "dev"
20
+ Project-URL: Homepage, https://github.com/amahlaka/multi-aws-tool
21
+ Project-URL: Repository, https://github.com/amahlaka/multi-aws-tool
22
+ Provides-Extra: dev
23
+
1
24
  # MultiAWSTool
2
25
 
3
26
  A command-line tool for managing multiple AWS accounts through AWS SSO. Execute AWS CLI commands across multiple accounts safely and efficiently with built-in security controls and parallel execution support.
@@ -11,12 +34,13 @@ A command-line tool for managing multiple AWS accounts through AWS SSO. Execute
11
34
  - **Security Controls**: Built-in protection against destructive operations with configurable overrides
12
35
  - **Shell Completion**: Full shell completion support for bash, zsh, and fish
13
36
  - **Library Integration**: Import as a Python library for use in other tools and scripts
37
+ - **MCP Server**: Use your accounts and profiles from Claude Desktop / Claude Code via a local MCP server
14
38
 
15
39
  ## Installation
16
40
 
17
41
  ### Option 1: Install as Package (Recommended)
18
42
 
19
- Install MultiAWSTool as a Python package to get the `multi-aws` command:
43
+ Requires Python 3.11 or newer. Install MultiAWSTool as a Python package to get the `multi-aws` command:
20
44
 
21
45
  ```bash
22
46
  # Clone the repository
@@ -78,6 +102,16 @@ echo "source ~/.multi-aws-completion.zsh" >> ~/.zshrc
78
102
 
79
103
  ## Quick Start
80
104
 
105
+ The fastest way to get going is the guided setup. It checks the AWS CLI, adds your SSO session,
106
+ logs you in, discovers your accounts, fetches roles, creates profiles, verifies access and
107
+ optionally connects Claude Desktop. It's safe to re-run, because finished steps are skipped:
108
+
109
+ ```bash
110
+ multi-aws setup
111
+ ```
112
+
113
+ Or step by step:
114
+
81
115
  1. **Install the tool** (see Installation section above)
82
116
 
83
117
  2. **Configure the tool**:
@@ -117,6 +151,12 @@ multi-aws run 'ec2 describe-instances' --accounts all --parallel --save
117
151
  multi-aws run 'iam list-users' --team production --timeout 60
118
152
  ```
119
153
 
154
+ **Commands with their own options** (quote the whole command, or put it after `--`):
155
+ ```bash
156
+ multi-aws run "ec2 describe-instances --query 'Reservations[].Instances[].InstanceId'" --accounts 123456789012
157
+ multi-aws run --accounts 123456789012 -- ec2 describe-instances --query 'Reservations[].Instances[].InstanceId'
158
+ ```
159
+
120
160
  **Dry run to see what would be executed**:
121
161
  ```bash
122
162
  multi-aws run 'ec2 terminate-instances --instance-ids i-1234567890abcdef0' --accounts 123456789012 --dry-run
@@ -125,6 +165,7 @@ multi-aws run 'ec2 terminate-instances --instance-ids i-1234567890abcdef0' --acc
125
165
  ## Commands
126
166
 
127
167
  ### Core Commands
168
+ - **`setup`**: Guided first-time setup (SSO session, login, accounts, roles, profiles, Claude)
128
169
  - **`configure`**: Interactive setup of tool configuration
129
170
  - **`init`**: Initialize SSO authentication and discover AWS accounts
130
171
  - **`roles`**: Fetch available IAM roles for specified accounts
@@ -262,6 +303,48 @@ print(f"Success rate: {summary.success_rate:.1f}%")
262
303
 
263
304
  For detailed library usage, see [LIBRARY_USAGE.md](LIBRARY_USAGE.md) and [OUTPUT_MODULE.md](OUTPUT_MODULE.md).
264
305
 
306
+ ## Using from Claude (MCP server)
307
+
308
+ `multi-aws-mcp` is a local [MCP](https://modelcontextprotocol.io) server (stdio) that gives
309
+ Claude Desktop, Claude Code and other MCP clients the whole tool: onboarding, SSO, account
310
+ discovery, roles, profiles, teams, tags, templates and running commands. It uses the same
311
+ config, account data, SSO session and AWS CLI profiles as the `multi-aws` CLI, and runs on your
312
+ machine, so credentials never leave it.
313
+
314
+ ```bash
315
+ multi-aws-mcp --install-claude-desktop # adds it to claude_desktop_config.json (keeps a .bak)
316
+ ```
317
+
318
+ Restart Claude Desktop afterwards. For Claude Code:
319
+
320
+ ```bash
321
+ claude mcp add multi-aws -- multi-aws-mcp
322
+ ```
323
+
324
+ `multi-aws-mcp --print-config` prints the JSON entry if you'd rather edit the config yourself.
325
+
326
+ **New users:** pick the **"Set up multi-aws"** prompt (`getting_started`) in Claude, or just ask
327
+ "help me set up multi-aws". Claude checks what's missing and walks you through adding your SSO
328
+ session, logging in, discovering accounts, fetching roles and creating profiles.
329
+
330
+ | Area | Tools |
331
+ |------|-------|
332
+ | Setup & status | `get_status` (setup checklist + next step), `get_config`, `update_config`, `list_sso_sessions`, `add_sso_session`, `sso_login` |
333
+ | Accounts & roles | `discover_accounts`, `list_accounts`, `fetch_roles` |
334
+ | Profiles | `generate_profiles`, `sync_profiles`, `sanitize_account_names`, `clean_duplicate_profiles` |
335
+ | Teams & tags | `list_teams`, `assign_team`, `set_tags`, `remove_tags`, `sync_tags` |
336
+ | Templates | `list_templates`, `save_template`, `delete_template`, `run_template` |
337
+ | Running | `run_aws_command` |
338
+ | Cleanup | `cleanup` (needs explicit confirmation) |
339
+
340
+ Safety:
341
+ - Destructive AWS commands follow `security.allow-destructive-commands` in your config. Claude can
342
+ neither override nor change that setting.
343
+ - Every edit to `~/.aws/config` keeps a timestamped backup next to it, and existing profiles are
344
+ updated in place rather than duplicated. Bulk operations support `dry_run`.
345
+ - Large command outputs are truncated in the response, and the full results are saved under
346
+ `<output path>/mcp/`.
347
+
265
348
  ## Output Structure
266
349
 
267
350
  MultiAWSTool generates structured output files that can be easily parsed by other tools:
@@ -420,4 +503,4 @@ MultiAWSTool/
420
503
 
421
504
  ## License
422
505
 
423
- MIT License
506
+ MIT License
@@ -1,18 +1,3 @@
1
- Metadata-Version: 2.4
2
- Name: multi-aws-tool
3
- Version: 0.1.2
4
- Summary: Multi AWS tool for managing operations across multiple AWS accounts via SSO
5
- Requires-Python: >=3.8
6
- Description-Content-Type: text/markdown
7
- Requires-Dist: click>=8.1
8
- Requires-Dist: boto3>=1.26.0
9
- Requires-Dist: configparser>=5.0.0
10
- Requires-Dist: pyyaml>=6.0
11
- Requires-Dist: colorama>=0.4.0
12
- Requires-Dist: tabulate>=0.9.0
13
- Project-URL: Homepage, https://github.com/amahlaka/multi-aws-tool
14
- Project-URL: Repository, https://github.com/amahlaka/multi-aws-tool
15
-
16
1
  # MultiAWSTool
17
2
 
18
3
  A command-line tool for managing multiple AWS accounts through AWS SSO. Execute AWS CLI commands across multiple accounts safely and efficiently with built-in security controls and parallel execution support.
@@ -26,12 +11,13 @@ A command-line tool for managing multiple AWS accounts through AWS SSO. Execute
26
11
  - **Security Controls**: Built-in protection against destructive operations with configurable overrides
27
12
  - **Shell Completion**: Full shell completion support for bash, zsh, and fish
28
13
  - **Library Integration**: Import as a Python library for use in other tools and scripts
14
+ - **MCP Server**: Use your accounts and profiles from Claude Desktop / Claude Code via a local MCP server
29
15
 
30
16
  ## Installation
31
17
 
32
18
  ### Option 1: Install as Package (Recommended)
33
19
 
34
- Install MultiAWSTool as a Python package to get the `multi-aws` command:
20
+ Requires Python 3.11 or newer. Install MultiAWSTool as a Python package to get the `multi-aws` command:
35
21
 
36
22
  ```bash
37
23
  # Clone the repository
@@ -93,6 +79,16 @@ echo "source ~/.multi-aws-completion.zsh" >> ~/.zshrc
93
79
 
94
80
  ## Quick Start
95
81
 
82
+ The fastest way to get going is the guided setup. It checks the AWS CLI, adds your SSO session,
83
+ logs you in, discovers your accounts, fetches roles, creates profiles, verifies access and
84
+ optionally connects Claude Desktop. It's safe to re-run, because finished steps are skipped:
85
+
86
+ ```bash
87
+ multi-aws setup
88
+ ```
89
+
90
+ Or step by step:
91
+
96
92
  1. **Install the tool** (see Installation section above)
97
93
 
98
94
  2. **Configure the tool**:
@@ -132,6 +128,12 @@ multi-aws run 'ec2 describe-instances' --accounts all --parallel --save
132
128
  multi-aws run 'iam list-users' --team production --timeout 60
133
129
  ```
134
130
 
131
+ **Commands with their own options** (quote the whole command, or put it after `--`):
132
+ ```bash
133
+ multi-aws run "ec2 describe-instances --query 'Reservations[].Instances[].InstanceId'" --accounts 123456789012
134
+ multi-aws run --accounts 123456789012 -- ec2 describe-instances --query 'Reservations[].Instances[].InstanceId'
135
+ ```
136
+
135
137
  **Dry run to see what would be executed**:
136
138
  ```bash
137
139
  multi-aws run 'ec2 terminate-instances --instance-ids i-1234567890abcdef0' --accounts 123456789012 --dry-run
@@ -140,6 +142,7 @@ multi-aws run 'ec2 terminate-instances --instance-ids i-1234567890abcdef0' --acc
140
142
  ## Commands
141
143
 
142
144
  ### Core Commands
145
+ - **`setup`**: Guided first-time setup (SSO session, login, accounts, roles, profiles, Claude)
143
146
  - **`configure`**: Interactive setup of tool configuration
144
147
  - **`init`**: Initialize SSO authentication and discover AWS accounts
145
148
  - **`roles`**: Fetch available IAM roles for specified accounts
@@ -277,6 +280,48 @@ print(f"Success rate: {summary.success_rate:.1f}%")
277
280
 
278
281
  For detailed library usage, see [LIBRARY_USAGE.md](LIBRARY_USAGE.md) and [OUTPUT_MODULE.md](OUTPUT_MODULE.md).
279
282
 
283
+ ## Using from Claude (MCP server)
284
+
285
+ `multi-aws-mcp` is a local [MCP](https://modelcontextprotocol.io) server (stdio) that gives
286
+ Claude Desktop, Claude Code and other MCP clients the whole tool: onboarding, SSO, account
287
+ discovery, roles, profiles, teams, tags, templates and running commands. It uses the same
288
+ config, account data, SSO session and AWS CLI profiles as the `multi-aws` CLI, and runs on your
289
+ machine, so credentials never leave it.
290
+
291
+ ```bash
292
+ multi-aws-mcp --install-claude-desktop # adds it to claude_desktop_config.json (keeps a .bak)
293
+ ```
294
+
295
+ Restart Claude Desktop afterwards. For Claude Code:
296
+
297
+ ```bash
298
+ claude mcp add multi-aws -- multi-aws-mcp
299
+ ```
300
+
301
+ `multi-aws-mcp --print-config` prints the JSON entry if you'd rather edit the config yourself.
302
+
303
+ **New users:** pick the **"Set up multi-aws"** prompt (`getting_started`) in Claude, or just ask
304
+ "help me set up multi-aws". Claude checks what's missing and walks you through adding your SSO
305
+ session, logging in, discovering accounts, fetching roles and creating profiles.
306
+
307
+ | Area | Tools |
308
+ |------|-------|
309
+ | Setup & status | `get_status` (setup checklist + next step), `get_config`, `update_config`, `list_sso_sessions`, `add_sso_session`, `sso_login` |
310
+ | Accounts & roles | `discover_accounts`, `list_accounts`, `fetch_roles` |
311
+ | Profiles | `generate_profiles`, `sync_profiles`, `sanitize_account_names`, `clean_duplicate_profiles` |
312
+ | Teams & tags | `list_teams`, `assign_team`, `set_tags`, `remove_tags`, `sync_tags` |
313
+ | Templates | `list_templates`, `save_template`, `delete_template`, `run_template` |
314
+ | Running | `run_aws_command` |
315
+ | Cleanup | `cleanup` (needs explicit confirmation) |
316
+
317
+ Safety:
318
+ - Destructive AWS commands follow `security.allow-destructive-commands` in your config. Claude can
319
+ neither override nor change that setting.
320
+ - Every edit to `~/.aws/config` keeps a timestamped backup next to it, and existing profiles are
321
+ updated in place rather than duplicated. Bulk operations support `dry_run`.
322
+ - Large command outputs are truncated in the response, and the full results are saved under
323
+ `<output path>/mcp/`.
324
+
280
325
  ## Output Structure
281
326
 
282
327
  MultiAWSTool generates structured output files that can be easily parsed by other tools:
@@ -435,4 +480,4 @@ MultiAWSTool/
435
480
 
436
481
  ## License
437
482
 
438
- MIT License
483
+ MIT License
@@ -6,7 +6,7 @@ This package can be used as a library to manage AWS accounts and SSO authenticat
6
6
  in other Python projects.
7
7
  """
8
8
 
9
- __version__ = "0.1.2"
9
+ __version__ = "0.2.0"
10
10
  __author__ = "MultiAWSTool Team"
11
11
  __description__ = "Multi AWS tool for managing operations across multiple AWS accounts via SSO"
12
12
 
@@ -29,6 +29,9 @@ from .output import (
29
29
  analyze_execution_summary
30
30
  )
31
31
 
32
+ # Programmatic multi-account execution
33
+ from .execution import execute, ExecutionError
34
+
32
35
  # Convenience imports for common use cases
33
36
  __all__ = [
34
37
  # Main management classes
@@ -54,6 +57,9 @@ __all__ = [
54
57
  'parse_execution_summary',
55
58
  'analyze_execution_summary',
56
59
 
60
+ # Execution
61
+ 'execute',
62
+
57
63
  # Utility classes
58
64
  'AccountDataManager',
59
65
 
@@ -62,4 +68,5 @@ __all__ = [
62
68
  'SSOAuthenticationError',
63
69
  'ConfigurationError',
64
70
  'AccountDataError',
71
+ 'ExecutionError',
65
72
  ]
@@ -4,12 +4,17 @@ Handles AWS account discovery, role enumeration, and account data management
4
4
  """
5
5
 
6
6
  import logging
7
- from typing import List, Optional, Dict
7
+ from typing import List, Optional, Dict, Set, Union
8
8
  from datetime import datetime
9
9
 
10
+ import boto3
11
+ import botocore.session
12
+
10
13
  from .sso_client import SSOClient, SSOAuthenticationError
14
+ from .organizations_client import OrganizationsClient, OrganizationsAccessError
11
15
  from ..models.account import Account, AccountCollection, AccountStatus, Role
12
16
  from ..utils.account_data import AccountDataManager, AccountDataError
17
+ from ..utils.validators import build_profile_name
13
18
 
14
19
  logger = logging.getLogger(__name__)
15
20
 
@@ -20,7 +25,7 @@ class AccountManager:
20
25
  """Manages AWS accounts, roles, and their data persistence"""
21
26
 
22
27
  def __init__(self, sso_session_name: str = "default", region: str = "us-east-1",
23
- account_file_path: Optional[str] = None):
28
+ account_file_path: Optional[str] = None, profile_prefix: str = "multi-aws"):
24
29
  """
25
30
  Initialize account manager
26
31
 
@@ -28,7 +33,11 @@ class AccountManager:
28
33
  sso_session_name: SSO session name for authentication
29
34
  region: AWS region for SSO operations
30
35
  account_file_path: Optional custom path for account data file
36
+ profile_prefix: Prefix used for generated AWS CLI profiles
37
+ (the ``general.prefix`` config value)
31
38
  """
39
+ self.region = region
40
+ self.profile_prefix = profile_prefix
32
41
  self.sso_client = SSOClient(sso_session_name, region)
33
42
  self.data_manager = AccountDataManager(account_file_path)
34
43
 
@@ -301,6 +310,190 @@ class AccountManager:
301
310
  accounts = self.get_active_accounts()
302
311
  return [account for account in accounts if account.has_role(role_name)]
303
312
 
313
+ def get_accounts_by_tags(self, tags: Dict[str, str]) -> List[Account]:
314
+ """
315
+ Get accounts that match all specified tags.
316
+
317
+ Args:
318
+ tags: Dict of tag key/value pairs that accounts must have
319
+
320
+ Returns:
321
+ List of accounts matching all supplied tags
322
+ """
323
+ collection = self.data_manager.load_accounts()
324
+ return collection.get_accounts_by_tags(tags)
325
+
326
+ def sync_account_tags(self, profile_name: Optional[str] = None) -> Dict[str, int]:
327
+ """
328
+ Sync account tags from AWS Organizations and persist them locally.
329
+
330
+ Fetches tags for every account in the local data file using the
331
+ Organizations ``list_tags_for_resource`` API. Falls back cleanly
332
+ when Organizations access is unavailable for any account.
333
+
334
+ Args:
335
+ profile_name: AWS profile with Organizations access (management /
336
+ delegated-admin account). If *None*, the default
337
+ credential chain is used.
338
+
339
+ Returns:
340
+ Dict with keys ``synced``, ``skipped``, and ``failed`` containing
341
+ the respective per-account counts.
342
+
343
+ Raises:
344
+ AccountManagerError: If the account data cannot be saved.
345
+ """
346
+ collection = self.data_manager.load_accounts()
347
+ accounts = collection.accounts
348
+
349
+ if not accounts:
350
+ logger.info("No accounts in local data; nothing to sync")
351
+ return {'synced': 0, 'skipped': 0, 'failed': 0}
352
+
353
+ org_client = OrganizationsClient(profile_name=profile_name)
354
+
355
+ synced = 0
356
+ skipped = 0
357
+ failed = 0
358
+
359
+ for account in accounts:
360
+ try:
361
+ tags = org_client.get_tags_for_account(account.id)
362
+ if tags:
363
+ account.tags = tags
364
+ account.last_updated = datetime.now()
365
+ synced += 1
366
+ logger.info(
367
+ f"Synced {len(tags)} tag(s) for account "
368
+ f"{account.id} ({account.name})"
369
+ )
370
+ else:
371
+ skipped += 1
372
+ logger.debug(
373
+ f"No tags returned for account {account.id} "
374
+ f"({account.name})"
375
+ )
376
+ except OrganizationsAccessError as exc:
377
+ logger.error(
378
+ f"Organizations access error for account {account.id}: {exc}"
379
+ )
380
+ failed += 1
381
+ except Exception as exc:
382
+ logger.error(
383
+ f"Unexpected error syncing tags for account {account.id}: {exc}"
384
+ )
385
+ failed += 1
386
+
387
+ if synced > 0:
388
+ try:
389
+ self.data_manager.save_accounts(collection)
390
+ except AccountDataError as exc:
391
+ raise AccountManagerError(
392
+ f"Failed to save synced tag data: {exc}"
393
+ ) from exc
394
+
395
+ logger.info(
396
+ f"Tag sync complete: {synced} synced, {skipped} skipped, "
397
+ f"{failed} failed"
398
+ )
399
+ return {'synced': synced, 'skipped': skipped, 'failed': failed}
400
+
401
+ # ------------------------------------------------------------------
402
+ # Profiles and boto3 sessions
403
+ # ------------------------------------------------------------------
404
+
405
+ @staticmethod
406
+ def _available_profiles() -> Set[str]:
407
+ """Profiles currently defined in the AWS config/credentials files."""
408
+ return set(botocore.session.Session().available_profiles)
409
+
410
+ def get_profile_name(self, account_id: Union[str, Account], role: Optional[str] = None) -> Optional[str]:
411
+ """
412
+ Resolve the AWS CLI profile name for an account (and optionally a role).
413
+
414
+ Without ``role`` the account's stored profile is returned. With ``role``,
415
+ the stored profile is used if it was generated for that role, otherwise
416
+ the conventional ``<prefix>-<account-name>-<role>`` name is tried.
417
+ Only profiles that actually exist in the AWS config are returned.
418
+
419
+ Args:
420
+ account_id: AWS account ID (or an :class:`Account` object)
421
+ role: Optional SSO role (permission set) name
422
+
423
+ Returns:
424
+ The profile name, or None if no matching profile is configured
425
+ """
426
+ account = account_id if isinstance(account_id, Account) else self.get_account(account_id)
427
+ if not account:
428
+ return None
429
+
430
+ candidates: List[str] = []
431
+ if account.profile_name and (role is None or account.profile_name.endswith(f"-{role}")):
432
+ candidates.append(account.profile_name)
433
+ if role:
434
+ candidates.append(build_profile_name(self.profile_prefix, account.name, role))
435
+
436
+ available = self._available_profiles()
437
+ return next((name for name in candidates if name in available), None)
438
+
439
+ def get_session(self, account_id: str, role: Optional[str] = None,
440
+ region: Optional[str] = None) -> boto3.Session:
441
+ """
442
+ Get a ready-to-use boto3 session for an account.
443
+
444
+ Uses the account's configured AWS CLI profile when one exists (see
445
+ :meth:`get_profile_name`), so credentials refresh through the normal
446
+ SSO profile flow. If no profile is configured and ``role`` is given,
447
+ temporary credentials are fetched directly from SSO
448
+ (``GetRoleCredentials``); these do not auto-refresh.
449
+
450
+ Args:
451
+ account_id: AWS account ID
452
+ role: Optional SSO role name (required when the account has no profile)
453
+ region: Region for the session; defaults to the manager's region
454
+
455
+ Returns:
456
+ A configured ``boto3.Session``
457
+
458
+ Raises:
459
+ AccountManagerError: If the account is unknown or no credentials
460
+ can be obtained
461
+ """
462
+ region = region or self.region
463
+ account = self.get_account(account_id)
464
+ if not account:
465
+ raise AccountManagerError(
466
+ f"Account {account_id} not found in local data. Run account discovery first."
467
+ )
468
+
469
+ profile_name = self.get_profile_name(account, role)
470
+ if profile_name:
471
+ return boto3.Session(profile_name=profile_name, region_name=region)
472
+
473
+ if not role:
474
+ raise AccountManagerError(
475
+ f"No AWS profile configured for account {account_id} ({account.name}). "
476
+ "Generate one with 'multi-aws profiles' or pass a role name."
477
+ )
478
+
479
+ try:
480
+ creds = self.sso_client._get_sso_client().get_role_credentials(
481
+ roleName=role,
482
+ accountId=account_id,
483
+ accessToken=self.sso_client.get_access_token(),
484
+ )['roleCredentials']
485
+ except Exception as e:
486
+ raise AccountManagerError(
487
+ f"Failed to get SSO credentials for role '{role}' in account {account_id}: {e}"
488
+ ) from e
489
+
490
+ return boto3.Session(
491
+ aws_access_key_id=creds['accessKeyId'],
492
+ aws_secret_access_key=creds['secretAccessKey'],
493
+ aws_session_token=creds['sessionToken'],
494
+ region_name=region,
495
+ )
496
+
304
497
  def is_authenticated(self) -> bool:
305
498
  """Check if SSO is authenticated"""
306
499
  return self.sso_client.is_authenticated()
@@ -0,0 +1,119 @@
1
+ """
2
+ AWS Organizations client for MultiAWSTool
3
+ Handles fetching account tags from AWS Organizations with graceful fallback
4
+ """
5
+
6
+ import boto3
7
+ import logging
8
+ from typing import Dict, List, Optional
9
+ from botocore.exceptions import ClientError
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ # Error codes that indicate Organizations is not accessible (not a hard failure)
14
+ _UNAVAILABLE_ERRORS = frozenset({
15
+ 'AccessDenied',
16
+ 'AccessDeniedException',
17
+ 'AWSOrganizationsNotInUseException',
18
+ 'AccountNotFoundException',
19
+ 'InvalidInputException',
20
+ 'ServiceException',
21
+ 'TooManyRequestsException',
22
+ })
23
+
24
+
25
+ class OrganizationsAccessError(Exception):
26
+ """Raised when Organizations API is unexpectedly inaccessible"""
27
+
28
+
29
+ class OrganizationsClient:
30
+ """Client for fetching account metadata from AWS Organizations"""
31
+
32
+ def __init__(self, profile_name: Optional[str] = None, region: str = "us-east-1"):
33
+ """
34
+ Initialize Organizations client.
35
+
36
+ Args:
37
+ profile_name: AWS profile name with Organizations access.
38
+ If None, uses the default credential chain.
39
+ region: AWS region for the Organizations API endpoint.
40
+ """
41
+ self.profile_name = profile_name
42
+ self.region = region
43
+ self._client = None
44
+
45
+ def _get_client(self):
46
+ """Lazily create and return the boto3 Organizations client."""
47
+ if self._client is None:
48
+ session = (
49
+ boto3.Session(profile_name=self.profile_name)
50
+ if self.profile_name
51
+ else boto3.Session()
52
+ )
53
+ self._client = session.client('organizations', region_name=self.region)
54
+ return self._client
55
+
56
+ def get_tags_for_account(self, account_id: str) -> Dict[str, str]:
57
+ """
58
+ Fetch tags for a single AWS account from Organizations.
59
+
60
+ Returns an empty dict if Organizations access is unavailable, so
61
+ callers can treat no-tags the same as an unfetched state.
62
+
63
+ Args:
64
+ account_id: 12-digit AWS account ID
65
+
66
+ Returns:
67
+ Dict mapping tag key to tag value (may be empty)
68
+ """
69
+ try:
70
+ client = self._get_client()
71
+ tags: Dict[str, str] = {}
72
+
73
+ paginator = client.get_paginator('list_tags_for_resource')
74
+ for page in paginator.paginate(ResourceId=account_id):
75
+ for tag in page.get('Tags', []):
76
+ tags[tag['Key']] = tag['Value']
77
+
78
+ logger.debug(
79
+ f"Fetched {len(tags)} tag(s) for account {account_id}"
80
+ )
81
+ return tags
82
+
83
+ except ClientError as exc:
84
+ error_code = exc.response['Error']['Code']
85
+ if error_code in _UNAVAILABLE_ERRORS:
86
+ logger.warning(
87
+ f"Organizations access unavailable for account {account_id} "
88
+ f"(error: {error_code}); skipping tags"
89
+ )
90
+ return {}
91
+ raise OrganizationsAccessError(
92
+ f"Failed to fetch tags for account {account_id}: {exc}"
93
+ ) from exc
94
+
95
+ except Exception as exc: # pragma: no cover – unexpected SDK errors
96
+ logger.warning(
97
+ f"Unexpected error fetching Organizations tags for account "
98
+ f"{account_id}: {exc}"
99
+ )
100
+ return {}
101
+
102
+ def get_tags_for_accounts(
103
+ self, account_ids: List[str]
104
+ ) -> Dict[str, Dict[str, str]]:
105
+ """
106
+ Fetch tags for multiple AWS accounts.
107
+
108
+ Falls back cleanly per-account when Organizations access is unavailable.
109
+
110
+ Args:
111
+ account_ids: List of 12-digit AWS account IDs
112
+
113
+ Returns:
114
+ Dict mapping account_id -> tag dict
115
+ """
116
+ results: Dict[str, Dict[str, str]] = {}
117
+ for account_id in account_ids:
118
+ results[account_id] = self.get_tags_for_account(account_id)
119
+ return results