AWS SSO Library

1.14.0 · active · verified Thu Apr 16

aws-sso-lib is a Python library designed to programmatically interact with AWS IAM Identity Center (formerly AWS SSO). It simplifies tasks like interactive login, obtaining `boto3` sessions for specific accounts and roles, and discovering available accounts and roles. It is the underlying library for the `aws-sso-util` CLI tool. The library's release cadence is tied to its dependent CLI, with irregular updates addressing new features, bug fixes, and compatibility with AWS SDKs.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to perform an interactive SSO login and then obtain a `boto3` session for a specific AWS account and role using `aws-sso-lib`. It then uses this session to call `sts.get_caller_identity()` and `s3.list_buckets()` as an example of AWS service interaction. Ensure `AWS_SSO_START_URL`, `AWS_SSO_REGION`, `AWS_ACCOUNT_ID`, `AWS_ROLE_NAME`, and `AWS_REGION` environment variables are set or replaced with your actual values.

import os
from aws_sso_lib import login, get_boto3_session

# Ensure these environment variables are set or replace with actual values
SSO_START_URL = os.environ.get('AWS_SSO_START_URL', 'https://d-xxxxxxxxxx.awsapps.com/start')
SSO_REGION = os.environ.get('AWS_SSO_REGION', 'us-east-1') # The region where your SSO instance is configured

# You might need to know the account ID and role name for your target AWS account
TARGET_ACCOUNT_ID = os.environ.get('AWS_ACCOUNT_ID', '123456789012')
TARGET_ROLE_NAME = os.environ.get('AWS_ROLE_NAME', 'AWSAdministratorAccess')
AWS_SESSION_REGION = os.environ.get('AWS_REGION', 'us-east-1') # The region for the Boto3 session

print("Attempting SSO login...")
# The 'login' function opens a browser for authentication if credentials are expired
# or not found. It returns a token dict which is cached.
token = login(SSO_START_URL, SSO_REGION, force_refresh=False)
print("SSO login successful (or token was already valid).")

print(f"Getting boto3 session for account {TARGET_ACCOUNT_ID} with role {TARGET_ROLE_NAME} in region {AWS_SESSION_REGION}...")
# Get a boto3 session using the SSO credentials
session = get_boto3_session(
    SSO_START_URL,
    SSO_REGION,
    TARGET_ACCOUNT_ID,
    TARGET_ROLE_NAME,
    region=AWS_SESSION_REGION,
    login=True # Automatically logs in if session is expired
)

# Use the session to interact with AWS services
sts_client = session.client('sts')
caller_identity = sts_client.get_caller_identity()
print(f"Successfully obtained credentials for: {caller_identity['Arn']}")

# Example: List S3 buckets
s3_client = session.client('s3')
buckets = s3_client.list_buckets()
print("S3 Buckets:")
for bucket in buckets['Buckets']:
    print(f"- {bucket['Name']}")

view raw JSON →