API Reference
This section provides detailed documentation for all public classes and functions in AWS SSO Manager.
AWSsso Class
The main class for managing AWS SSO credentials.
- class aws_sso.AWSsso(aws_exec_file_path: str = 'C:\\Program Files\\Amazon\\AWSCLIV2\\aws.exe', db_path: Path = PosixPath('data/aws_credentials.db'), refresh_window_hours: int = 6, max_retries: int = 3, retry_delay: int = 5)[source]
Bases:
object
A class to handle AWS SSO authentication and credential management. This class provides functionality to refresh AWS SSO credentials and track their validity.
Examples
```python # Example 1: Basic usage sso = AWSsso(
aws_exec_file_path=r’C:Program FilesAmazonAWSCLIV2ws.exe’, db_path=Path(‘./data/credentials.db’), refresh_window_hours=6
)
# Get credential expiration time expiration = sso.get_expiration_time() print(f”Credentials will expire at: {expiration}”)
# Example 2: Custom configuration sso = AWSsso(
aws_exec_file_path=r’C:Program FilesAmazonAWSCLIV2ws.exe’, db_path=Path(‘./data/custom_credentials.db’), refresh_window_hours=12, # Refresh every 12 hours max_retries=5, # More retries retry_delay=10 # Longer delay between retries
)
# Ensure credentials are valid before AWS operations try:
sso.ensure_valid_credentials() # Proceed with AWS operations
- except AuthenticationError as e:
print(f”Failed to authenticate: {e}”)
# Monitor credential status last_refresh = sso.get_last_refresh_time() if last_refresh:
time_since_refresh = datetime.now() - last_refresh print(f”Time since last refresh: {time_since_refresh}”)
- __exit__(exc_type, exc_val, exc_tb) None [source]
Context manager exit - ensure database connection is closed.
- __init__(aws_exec_file_path: str = 'C:\\Program Files\\Amazon\\AWSCLIV2\\aws.exe', db_path: Path = PosixPath('data/aws_credentials.db'), refresh_window_hours: int = 6, max_retries: int = 3, retry_delay: int = 5)[source]
Initialize the AWS SSO handler.
- Parameters:
aws_exec_file_path (str) – Path to the AWS CLI executable
db_path (Path) – Path to the credentials database
refresh_window_hours (int) – Hours between credential refreshes
max_retries (int) – Maximum number of authentication retries
retry_delay (int) – Delay between retries in seconds
- Raises:
ValueError – If configuration parameters are invalid
CredentialError – If there’s an error initializing the database
- _get_db_connection() Connection [source]
Get a database connection, creating one if it doesn’t exist.
- Returns:
A database connection instance
- Return type:
sqlite3.Connection
- Raises:
CredentialError – If there’s an error creating the connection
- _init_db() None [source]
Initialize the SQLite database for storing credential timestamps. If the database exists and contains timestamps, initialize the cached timestamps.
- Raises:
CredentialError – If there’s an error creating the database or table
- ensure_valid_credentials() bool [source]
Ensure that the AWS SSO credentials are valid. If credentials are expired or about to expire, they will be refreshed.
- Returns:
True if credentials are valid or were successfully refreshed
- Return type:
bool
- Raises:
AuthenticationError – If there’s an error during SSO authentication
CredentialError – If there’s an error updating the timestamp
- get_expiration_time() datetime | None [source]
Get the expiration time of the current credentials.
- Returns:
The expiration time of the credentials, or None if not set
- Return type:
Optional[datetime]
- get_last_refresh_time() datetime | None [source]
Get the last time the credentials were refreshed.
- Returns:
The last refresh time, or None if not set
- Return type:
Optional[datetime]
- refresh_credentials() bool [source]
Refresh AWS SSO credentials using the AWS CLI if they need refreshing.
- Returns:
True if credentials are valid or were successfully refreshed, False otherwise
- Return type:
bool
- Raises:
AuthenticationError – If there’s an error during SSO authentication
CredentialError – If there’s an error updating the timestamp
- property should_refresh_credentials: bool
Check if credentials need to be refreshed.
- Returns:
True if credentials need to be refreshed, False otherwise
- Return type:
bool
Key Methods
__init__(aws_exec_file_path, db_path, refresh_window_hours=6, max_retries=3, retry_delay=5)
: Initialize the AWS SSO managerensure_valid_credentials()
: Check and refresh credentials if neededget_expiration_time()
: Get the expiration time of current credentialsget_last_refresh_time()
: Get the timestamp of the last credential refreshrefresh_credentials()
: Force a credential refreshshould_refresh_credentials()
: Check if credentials need refreshing
Example Usage
from aws_sso import AWSsso
from pathlib import Path
# Initialize with custom settings
sso = AWSsso(
aws_exec_file_path='/usr/local/bin/aws', # Adjust for your system
db_path=Path('./credentials.db'),
refresh_window_hours=12,
max_retries=5,
retry_delay=10
)
# Use as context manager
with sso:
sso.ensure_valid_credentials()
if sso.should_refresh_credentials():
sso.refresh_credentials()
Exceptions
Custom exceptions for error handling.
AuthenticationError
- exception aws_sso.exceptions.AuthenticationError[source]
Bases:
Exception
Exception raised for authentication related errors.
- Raised when AWS SSO authentication fails. Common causes:
Invalid AWS SSO configuration
Network connectivity issues
Expired SSO session
Example handling:
try:
sso.ensure_valid_credentials()
except AuthenticationError as e:
print(f"Authentication failed: {e}")
# Handle authentication failure
CredentialError
- exception aws_sso.exceptions.CredentialError[source]
Bases:
Exception
Exception raised for credential related errors.
- Raised for credential-related issues. Common causes:
Database access errors
Invalid credential format
File permission issues
Example handling:
try:
expiration = sso.get_expiration_time()
except CredentialError as e:
print(f"Credential error: {e}")
# Handle credential error