Metadata-Version: 2.4
Name: sso-config-generator
Version: 1.6.1
Summary: Python tool for generating AWS SSO configuration and directory structure
Author-email: easytocloud <info@easytocloud.com>
License: MIT License
        
        Copyright (c) 2024 easytocloud
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/easytocloud/sso-config-generator
Project-URL: Repository, https://github.com/easytocloud/sso-config-generator
Project-URL: Issues, https://github.com/easytocloud/sso-config-generator/issues
Project-URL: Changelog, https://github.com/easytocloud/sso-config-generator/blob/main/CHANGELOG.md
Keywords: aws,sso,config,generator,cli,aws-cli
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Topic :: Software Development :: Build Tools
Classifier: Topic :: System :: Systems Administration
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: boto3>=1.34.0
Requires-Dist: click>=8.1.0
Requires-Dist: pyyaml>=6.0.1
Dynamic: license-file

# SSO Config Generator

A Python CLI tool for generating AWS CLI configuration and directory structures.

## The issue it solves

In a large organization with multiple AWS accounts, managing access via AWS SSO can become cumbersome. You may have access to many roles across various accounts, and switching between them manually can be error-prone and time-consuming.

sso-config-generator creates a profile for each AWS Role you have access to via AWS SSO. After logging in to an sso session, you can use the profiles in your AWS CLI commands, SDKs, and tools like Terraform.

```bash
aws sso login --profile sso-browser
```
The login command opens a browser window for authentication. After successful login, you can use the generated profiles like this:

```bash
aws s3 ls --profile my-profile-name
```
or set the `AWS_PROFILE` (or `AWS_DEFAULT_PROFILE`) environment variable:

```bash
export AWS_PROFILE=my-profile-name
aws s3 ls
```

It also creates a directory structure that mirrors your AWS Organization, making it easy to navigate and manage multiple AWS accounts. Each account directory contains a `.envrc` file (for use with `direnv`) that sets the `AWS_PROFILE` environment variable to the appropriate profile for that account, so that cd-ing into the directory automatically switches to the correct AWS profile.

## Profile Naming Convention
Profiles are named using the following convention:

```
<RoleName>@<AccountName>
```
For example, if you have access to the `AdministratorAccess` role in the `DevAccount`, the profile will be named:

```
AdministratorAccess@DevAccount
```

## Required SSO Browser Profile

All commands in this repo assume your `~/.aws/config` contains a reusable profile that points at your SSO session in the Organization Management Account. Make sure this block exists (adjust the region, account ID, and role name as needed):

```
[profile sso-browser]
sso_session = sso
sso_account_id = 123456789012          # Your Organization Management Account ID
sso_role_name = OrganizationAccountRole # Role name with Organizations permissions
region = eu-west-1
output = json
```

Run `aws sso login --profile sso-browser` before invoking `sso-config-generator` so the CLI can reuse the cached credentials.

### One-Time Setup: sso-browser Profile Configuration

The `sso-browser` profile is used to retrieve both SSO account information and AWS Organization structure. For full functionality (including OU hierarchy), the SSO role must have the necessary IAM permissions.

**Role Setup:**
1. In your AWS SSO console, assign a role to your user account in your **Organization Management Account** (master account)
2. The role name in SSO should match the `sso_role_name` you configured in the `sso-browser` profile (e.g., `OrganizationAccountRole`)
3. In your Organization Management Account, create or update the IAM role with the following trust relationship (for SSO):
   - Trust the SSO service in your region
4. Attach the following permissions policy to the IAM role:

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "sso:ListAccounts",
        "sso:ListAccountRoles",
        "organizations:ListRoots",
        "organizations:ListOrganizationalUnitsForParent",
        "organizations:DescribeOrganizationalUnit",
        "organizations:ListParents"
      ],
      "Resource": "*"
    }
  ]
}
```

**Alternative:** Instead of creating a custom role, you can use the AWS managed policy `OrganizationsReadOnlyAccess` which includes all the required permissions.

After setting up the role in SSO, run:
```bash
aws sso login --profile sso-browser
```

## Overview

SSO Config Generator is a standalone Python tool that simplifies AWS SSO configuration management by:

1. Generating properly configured AWS CLI config files
2. Creating directory structures that mirror your AWS Organization
3. Setting up environment files for easy role switching using `direnv`

## Installation

You can install sso-config-generator via pip, or use it directly without installation using `uvx`. 

```bash
pip install sso-config-generator
```

### Prerequisites

- Python 3.8 or higher
- AWS CLI v2 configured with:
  - Default region set in `~/.aws/config` or via `AWS_DEFAULT_REGION` environment variable
  - AWS SSO configured via `aws configure sso`
- `direnv` (optional, for automatic profile switching)

### AWS Configuration

Before using the tool, ensure you have:

1. Configure AWS SSO:
   Either run:
   ```bash
   aws configure sso
   # Follow the prompts to enter:
   # - SSO start URL (e.g., https://your-domain.awsapps.com/start)
   # - SSO Region
   # - SSO registration scopes (accept default)
   ```
   or manually edit `~/.aws/config` to look like this (the `[profile sso-browser]` block must match the one described in the **Required SSO Browser Profile** section):
   ```
   [sso-session sso]
   sso_region = eu-west-1
   sso_start_url = https://YOUR_DOMAIN.awsapps.com/start
   sso_registration_scopes = sso:account:access

   [profile sso-browser]
   sso_session = sso
   sso_account_id = 123456789012
   sso_role_name = OrganizationAccountRole
   output = json
   region = eu-west-1
   ```
2. Login to AWS SSO:
   ```bash
   # Login to SSO to create credentials
   aws sso login --profile sso-browser
   ```

### Cloud9/CloudX Integration

When running in AWS Cloud9 or CloudX environments, the tool will automatically:
1. Detect if you're in your home directory with an "environment" subdirectory
2. Change to the "environment" directory
3. Skip the SSO name in the directory structure

This ensures seamless operation in AWS-provided development environments.

### Troubleshooting

1. "Error: You must specify a region"
   - Use the `--region` flag: `uvx sso-config-generator --region us-east-1`
   - Or set AWS_DEFAULT_REGION environment variable
   - Or configure default region in ~/.aws/config

2. "Unable to locate credentials"
   - Run `aws sso login` to refresh your SSO credentials
   - Ensure you've completed AWS SSO configuration with `aws configure sso`
   - Check if your SSO session has expired (sessions typically last 8 hours)

3. "SSO session is expired"
   - Run `aws sso login` to start a new session

## Usage

### Basic Usage

Simply run:

```bash
uvx sso-config-generator
```

This will:
- Update your AWS CLI config file (`~/.aws/config`)
- Generate a directory structure in the current directory + sso-name
- Create `.envrc` files in each account directory with AdministratorAccess role
- Use OU structure for directory organization (cached for performance)

The tool caches OU structure information in the same directory as your AWS config file to improve performance.
Cache files are organization-scoped using the SSO start URL domain prefix (for example `https://my-easytocloud.awsapps.com/start` uses the cache key `my-easytocloud`).
If a cache file is older than 7 days, it is ignored and rebuilt automatically.
To force a full cache rebuild:

```bash
uvx sso-config-generator --rebuild-cache
```

### Command Options

```
Usage: sso-config-generator [OPTIONS]

Options:
  --create-directories/--no-create-directories  Create a directory for each account (default: True)
  --use-ou-structure/--no-use-ou-structure     Create directories for each OU (default: True)
  --developer-role-name NAME                   Role name to use for .envrc files (default: AdministratorAccess)
  --rebuild-cache                              Force rebuild of OU structure cache
  --sso-name NAME                              Use specified SSO name instead of extracting from SSO start URL
  --create-repos-md                            Create repos.md files in each account directory
  --skip-sso-name                              Do not create a directory for the SSO name (default: False)
  --unified-root PATH                          Directory where account directories are created
                                               (default: current directory)
                                               If current directory is named "environment", SSO name is
                                               automatically skipped
  --region REGION                              AWS region to use (default: eu-west-1)
  --validate                                   Validate current AWS SSO configuration instead of generating
  --help                                       Show this message and exit
  --version                                    Show the version and exit
```

### Examples

1. Basic config generation (uses defaults):
```bash
uvx sso-config-generator
```

2. Disable OU structure (flat account directories):
```bash
uvx sso-config-generator --no-use-ou-structure
```

3. Use different role for .envrc files:
```bash
uvx sso-config-generator --developer-role-name ReadOnlyAccess
```

4. Use specific AWS region:
```bash
uvx sso-config-generator --region us-east-1
```

5. Force rebuild of OU cache:
```bash
uvx sso-config-generator --rebuild-cache
```

5. Specify custom root directory:
```bash
uvx sso-config-generator --unified-root ~/aws-environments
```

6. Skip creating directories (config file only):
```bash
uvx sso-config-generator --no-create-directories
```

7. Working in an "environment" directory (automatic behavior):
```bash
# If your current directory is named 'environment'
cd environment
uvx sso-config-generator
# This will automatically skip creating the SSO name directory
```

8. Validate existing configuration:
```bash
uvx sso-config-generator --validate
```

## Development

### Setup Development Environment

1. Clone the repository:
```bash
git clone https://github.com/easytocloud/sso-config-generator.git
cd sso-config-generator
```

2. Create a virtual environment:
```bash
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
```

3. Install the package in development mode:
```bash
pip install -e .
```

### Common Development Tasks

- Build the package: `pip install build && python -m build`
- Run the tool: `uvx sso-config-generator`
- Test changes: `./test_sso_config.sh`

### Versioning

This project uses [semantic-release](https://github.com/semantic-release/semantic-release) for automated versioning and package publishing. The version is stored in a single source of truth:

- `src/sso_config_generator/version.py`: Contains the `__version__` variable
- `__init__.py` imports this version
- `pyproject.toml` is updated automatically by the GitHub workflow

When a commit is pushed to the main branch, the GitHub workflow:
1. Determines the next version based on commit messages
2. Creates a GitHub release and tag
3. Updates the version in version.py and pyproject.toml
4. Publishes the package to PyPI

To trigger specific version increments, use the following commit message prefixes:
- `feat:` - Minor version increment (e.g., 1.1.0 -> 1.2.0)
- `fix:`, `docs:`, `style:`, etc. - Patch version increment (e.g., 1.1.0 -> 1.1.1)

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
