Package: aws-sso-lib
aws-sso-libaws-sso-liballows you to programmatically interact with AWS IAM Identity Center (formerly AWS SSO).The primary functions that will be of interest are available at the package level:get_boto3_session: Get a boto3 session for a specific account and role.login: ensure the user is logged in to Identity Center, with dispatch to the browser.list_available_accountsandlist_available_roles: discover the access the user has.list_assignments: for admin purposes, iterate over all assignments in Identity Center, which is currently hard to do through the API.aws-sso-utilis a command-line utility built onaws-sso-libfor interacting with Identity Center; see the details of that projecthere.Installpip install --user aws-sso-lib
python -c "import aws_sso_lib; aws_sso_lib.login('https://my-start-url.awsapps.com/start', 'us-east-2')"get_boto3_sessionOften when writing a script, you know the exact account and role you want the script to use.
You could configure a profile in your~/.aws/configfor this (perhaps usingaws-sso-util configure profile), but especially if multiple people may be using the script, it's more convenient to have the configuration baked into the script itself.get_boto3_session()is the function to do that with.get_boto3_session(start_url,sso_region,account_id,role_name,*,region,login=False,sso_cache=None,credential_cache=None)start_url: [REQUIRED] The start URL for the Identity Center instance.sso_region: [REQUIRED] The AWS region for the Identity Center instance.account_id: [REQUIRED] The AWS account ID to use.role_name: [REQUIRED] The Identity Center role (aka PermissionSet) name to use.region: [REQUIRED] The AWS region for the boto3 session (note, required but keyword-only).login: Set toTrueto interactively log in the user if their Identity Center credentials have expired.sso_cache: A dict or dict-like object for Identity Center credential caching to replace the default file cache in~/.aws/sso/cache.credential_cache: A dict or dict-like object to cache the role credentials in to replace the default in-memory cache.Returns aboto3 Session objectconfigured for the account and role.For more control over the login process, use theloginfunction separately.loginWhile the functions that require the user to be logged in let you specifylogin=Trueto interactively log in the user if they are not already logged in, you can have more control over the process, or retrieve the access token, usinglogin().If the user is not logged in orforce_refreshisTrue, it will attempt to log in.
If the user is logged in andforce_refreshisFalse, no action is taken.Normally, it will attempt to automatically open the user's browser to log in, as well as printing the URL and code to stderr as a fallback. However, ifdisable_browserisTrue, or ifdisable_browserisNone(the default) and the environment variableAWS_SSO_DISABLE_BROWSERis set to1ortrue, only the message with the URL and code will be printed.A custom message can be printed by settingmessageto a template string using{url}and{code}as placeholders.
The message can be suppressed by settingmessagetoFalse.To fully control the communication with the user, use theuser_auth_handlerparameter.
It must be a callable taking four keyword arguments:verificationUri,userCode,verificationUriComplete, andexpiresAt(a datetime).
ProvideverificationUrianduserCodeto the user if they are expected to type them in manually (e.g., on a separate device);verificationUriCompletehas the userCode embedded in it, suitable for copying, linking, or a browser popup.
The function must return promptly or it will block the login process.login(start_url,sso_region,*,force_refresh=False,expiry_window=None,disable_browser=None,message=None,outfile=None,user_auth_handler=None,sso_cache=None)start_url: [REQUIRED] The start URL for the Identity Center instance.sso_region: [REQUIRED] The AWS region for the Identity Center instance.force_refresh: Set toTrueto always go through the authentication process.expiry_window: A datetime.timedelta (or number of seconds), or callable returning such, specifying the minimum duration any existing token must be valid for.disable_browser: Set toTrueto skip the browser popup and only print a message with the URL and code.message: A message template to print with the fallback URL and code, orFalseto suppress the message.outfile: The file-like object to print the message to (stderr by default)user_auth_handler: override browser popup and message printing and use the given function instead.sso_cache: A dict or dict-like object for Identity Center credential caching, to override the default file cache in~/.aws/sso/cache.Returns the token dict as returned bysso-oidc:CreateToken, which contains the actual authorization token, as well as the expiration.list_available_accountsandlist_available_rolesIdentity Center provides programmatic access to the permissions that a user has.
You can access this throughlist_available_accounts()andlist_available_roles().With both, you can setlogin=Trueto interactively log in the user if they are not already logged in.Note that these functions return iterators; they don't return a list, because the number of roles may be very large and you shouldn't have to wait for the entire list to be created to start processing.
You can always get a list by, for example,list(list_available_roles(...)).list_available_accounts(start_url,sso_region,*,login=False)start_url: The start URL for the Identity Center instance.sso_region: The AWS region for the Identity Center instance.login: Set toTrueto interactively log in the user if their Identity Center credentials have expired.Returns an iterator that yields account id and account name.list_available_roles(start_url,sso_region,account_id=None,*,login=False)start_url: [REQUIRED] The start URL for the Identity Center instance.sso_region: [REQUIRED] The AWS region for the Identity Center instance.account_id: Optional account id or list of account ids to check.If not set, all accounts available to the user are used.login: Set toTrueto interactively log in the user if their Identity Center credentials have expired.Returns an iterator that yields account id, account name, and role name.list_assignmentsThe Identity Center API only allows you tolist assignments for a specific accountandpermission set.
To find all your assignments, you need to iterate over all accounts, and then interate over all permission sets.list_assignments()does this work for you.Unlike the other functions list above, this uses admin APIs, which require AWS credentials, rather than taking as input a start URL and region.list_assignmentsreturns an iterator overAssignmentnamed tuples, which have the following fields:instance_arnprincipal_typeprincipal_idprincipal_namepermission_set_arnpermission_set_nametarget_typetarget_idtarget_nameThe name fields may beNone, if the names are not known or looked up.
By default, principal and permission set names are not retrieved, nor are account names for accounts that have been provided as explicit targets.If you don't specifyinstance_arnand/oridentity_store_id, these will be looked up using theListInstances API, which today returns at most one instance (with associated identity store).An assignment is the combination of a principal (a user or a group), a permission set, and a target (an AWS account).
For each of these values, you can provide either an explicit specification, or a filter function.You can provide an OU as a target, which will use all accounts in that OU, and optionally all accounts recursively in child OUs as well.list_assignments(session,instance_arn=None,identity_store_id=None,principal=None,principal_filter=None,permission_set=None,permission_set_filter=None,target=None,target_filter=None,get_principal_names=False,get_permission_set_names=False,get_target_names=False,ou_recursive=False)session: [REQUIRED] boto3 session to useinstance_arn: The Identity Center instance to use, or it will be looked up using ListInstancesidentity_store_id: The identity store to use if principal names are being retrieved or it will be looked up using ListInstancesprincipal: A principal specification or list of principal specifications.A principal specification is a principal id or a 2-tuple of principal type and id.principal_filter: A callable taking principal type, principal id, and principal name (which may beNone), and returningTrueif the principal should be included.permission_set: A permission set arn or id, or a list of the same.permission_set_filter: A callable taking permission set arn and name (name may beNone), returning True if the permission set should be included.target: A target specification or list of target specifications.A target specification is an account or OU id, or a 2-tuple of target type, which is either AWS_ACCOUNT or AWS_OU, and target id.target_filter: A callable taking target type, target id, and target name (which may beNone), and returningTrueif the target should be included.get_principal_names: Set toTrueto retrieve names for principals in assignments.get_permission_set_names: Set toTrueto retrieve names for permission sets in assignments.get_target_names: Set toTrueto retrieve names for targets in assignments, when they are explicitly provided as targets. For OUs as targets or if no targets are specified, the account names will be retrieved automatically during the enumeration process.ou_recursive: Set toTrueif an OU is provided as a target to get all accounts including those in child OUs.Returns an iterator overAssignmenttuples