This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
poetry install --with=dev --with=main- Install all dependencies including dev toolspoetry shell- Activate virtual environment for development
poetry run pytest- Run unit testspoetry run pytest --verbose --cov=./ --cov-report=xml- Run unit tests with coveragemake test-unit- Run unit tests in Docker (with coverage)make test-unit-no-cov- Run unit tests in Docker (no coverage)make test-int- Run integration tests using bats in Dockermake tests- Run full test suite (unit + integration)
poetry run black .- Format code with Black (line length: 120)poetry run pylint leverage/- Run lintingpoetry run pre-commit install- Install pre-commit hookspoetry run pre-commit run --all-files- Run pre-commit checks manually
make build- Build distributables (cleans first)make check- Check distributables with twinepoetry build- Build package using Poetrymake clean- Clean build artifacts
make build-image- Build Docker testing image- All test commands can run in Docker using the testing image
Leverage CLI is a Python-based command-line tool for managing Binbash Leverage projects. It uses host-based execution to run infrastructure tools directly on the system.
leverage/leverage.py- Main CLI entry point using Click frameworkleverage/modules/- Command modules (aws, terraform, kubectl, etc.)leverage/modules/runner.py- Generic binary runner base classleverage/modules/tfrunner.py- Terraform/OpenTofu-specific runnerleverage/conf.py- Configuration loading from build.env filesleverage/tasks.py- Task system for build scriptsleverage/path.py- Path utilities and git repository handling
- Module System: Commands are organized in modules under
leverage/modules/ - Host-Based Execution: Direct execution of system binaries (terraform, tofu, kubectl, etc.)
- Runner Architecture: Generic Runner class with specialized subclasses (TFRunner)
- Configuration Management: Hierarchical loading of build.env files
- Task System: Decorator-based task definition system for build scripts
- AWS Integration: Extensive AWS credential and service management via SSO/MFA
The CLI follows this pattern:
leverage [global-options] <module> <subcommand> [args]
Key modules include:
project- Project initialization and managementterraform/tf/tofu- Terraform/OpenTofu operationsaws- AWS service interactionscredentials- Credential managementkubectl/kc- Kubernetes operationsrun- Custom task executionshell- Interactive shell access
- Supports Python 3.9-3.13
- Version defined in
leverage/__init__.py - Binary version validation on initialization (for TFRunner)
- Uses
build.envfiles for project configuration - Hierarchical loading from project root to current directory
- Environment-specific overrides supported
The CLI executes infrastructure tools directly on the host system using the Runner architecture.
Generic command runner base class:
- Purpose: Provides common execution functionality for all binary runners
- Binary Discovery: Searches for binaries in PATH or accepts absolute paths
- Environment Management: Merges instance-level and run-time environment variables
- Execution Modes:
run()- Interactive execution (returns exit code) or silent (returns exit code, stdout, stderr)exec()- Convenience method for non-interactive execution with output capture
- Working Directory: Supports execution in any specified directory
- Validation: Automatic binary existence validation on initialization
Terraform/OpenTofu-specific runner extending Runner:
- Binaries: Uses system-installed
terraformortofubinaries - Configuration: Accepts
terraform=Truefor Terraform, defaults to OpenTofu - Binary Validation: Validates binary type by checking
--versionoutput- Ensures
tofubinary is actually OpenTofu (not Terraform) - Ensures
terraformbinary is actually Terraform (not OpenTofu)
- Ensures
- Error Messages: Provides installation URLs when binaries are not found
- Environment Variables: Initialized with AWS credential file paths via
env_varsparameter
CLI Entry Points:
tofu- Creates TFRunner with OpenTofu binary (tofu)terraform- Creates TFRunner with Terraform binary (terraform)- Both set up credential environment variables for AWS config and credentials files
Command Decorators:
@pass_runner- Injects TFRunner instance from Click context@pass_paths- Injects PathsHandler instance for file/directory management
Supported Commands:
init- Layer initialization with backend configuration injectionplan- Execution plan generation with auto-discovered tfvarsapply- Infrastructure changes with conditional tfvars injectiondestroy- Infrastructure destructionoutput- Output variable displayversion- Binary version displayformat- Code formatting (recursive by default)force-unlock- State file lock removalvalidate- Configuration validationvalidate-layout- Leverage convention validationimport- Resource importrefresh-credentials- AWS credential refresh
Multi-Layer Support:
--layersoption for operating on multiple layers from account directory- Layer validation and backend key management via
invoke_for_all_commands() - Automatic backend key generation based on layer path structure
Uses generic Runner class to execute kubectl binary:
- Binary: System-installed
kubectl - Configuration: Sets KUBECONFIG environment variable to project-specific path
- AWS Integration: Configures kubectl contexts for EKS clusters
- Commands:
configure- Add EKS cluster from current layer to kubectl configdiscover- Scan for cluster metadata files and configure selected cluster
- All other kubectl commands pass through to the binary
Uses generic Runner class to execute tfautomv binary:
- Binary: System-installed
tfautomv - Configuration: Passes terraform binary path via
--terraform-binflag - Integration: Uses same tfvars discovery as Terraform/OpenTofu commands
Token Validation (check_sso_token()):
- Validates SSO token existence in cache directory (
~/.aws/sso/cache/<sso_role>) - Checks token expiration against current time
- Provides clear error messages for missing or expired tokens
Credential Refresh (refresh_layer_credentials()):
- Parses Terraform files to discover required AWS profiles
- Uses boto3 SSO client to retrieve temporary credentials
- Updates AWS config file with credential expiration timestamps
- Writes temporary credentials to AWS credentials file
- Implements 30-minute early renewal to avoid mid-operation expiration
- Supports cross-account profile resolution
Profile Discovery (get_profiles()):
- Scans
config.tf,locals.tf,runtime.tffor profile references - Extracts profile variables from Terraform configurations
- Reads backend profile from
backend.tfvars
- Discovers all
*.tfvarsfiles incommon/directory - Discovers all
*.tfvarsfiles in account-specific directory - Returns as
-var-file=<path>arguments for Terraform/OpenTofu - Used automatically in plan, destroy, validate, and conditionally in apply
- Backend config file path injected during
initcommand - Automatic backend key generation in
invoke_for_all_commands() - Backend key validation in
validate_layout() - Support for legacy naming conventions (tf- vs terraform-, base- vs tools-)
- User runs
leverage tofu|terraform <command> [args] - Click creates TFRunner instance with credential environment variables
- Command function decorated with
@pass_runnerand@pass_paths - Authentication check via
check_sso_token(paths) - Credential refresh via
refresh_layer_credentials(paths) - TFRunner.run() executes binary with:
- Merged environment variables (instance + runtime)
- Specified working directory
- Auto-discovered tfvars (for applicable commands)
- User-provided arguments
- Exit code returned to CLI
- User runs command with
--layers layer1,layer2from account directory invoke_for_all_commands()validates all layers- Backend keys generated/validated for each layer
- Command executed sequentially for each layer with layer-specific working directory
For full functionality, ensure the following binaries are installed and available in PATH:
Required:
terraformortofu- For Terraform/OpenTofu operationsaws- AWS CLI for SSO authentication (via boto3)- Python 3.9-3.13
Optional:
kubectl- For Kubernetes operationstfautomv- For TFAutomv operations
- Performance: Direct binary execution without overhead
- Flexibility: Use any installed tool version (including custom builds)
- IDE Integration: Better debugging and tooling support
- Simplicity: Standard environment variables and execution
- Plugin Compatibility: Native Terraform/OpenTofu plugin caching
- Development Speed: Faster iteration during development