How can I query UserId for AWS SSO Users using Boto3

Viewed 29

How can I get UserId for AWS SSO Users using Boto3.

I wanted to use it to assign permissions to a user for a specific aws account using below code, however, this requires PrincipalId which is some 16-20 digit number associated with each user and is called User ID in the AWS console.

You can read about it - here

response = client.create_account_assignment(
    InstanceArn='string',
    TargetId='string',
    TargetType='AWS_ACCOUNT',
    PermissionSetArn='string',
    PrincipalType='USER'|'GROUP',
    PrincipalId='string'
)
1 Answers

If you have the UserName for the user you'd like to assign permissions for, you can programmatically use IAM to determine that user's UserId:

import boto3

# Get the UserId.
user_name = 'the user name here'
iam_client = boto3.client('iam')
result = iam_client.get_user(UserName=user_name)
user_id = result['User']['UserId']

# Assign permissions to the UserId.
sso_admin_client = boto3.client('sso-admin')
response = sso_admin_client.create_account_assignment(
    InstanceArn='string',
    TargetId='string',
    TargetType='AWS_ACCOUNT',
    PermissionSetArn='string',
    PrincipalType='USER',
    PrincipalId=user_id
)
Related