skip to Main Content

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'
)

2

Answers


  1. 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
    )
    
    Login or Signup to reply.
  2. You’ll also need to use the ‘identitystore’ to get user or group IDs. Try this from the docs –

    import boto3
    
    client = boto3.client('identitystore')
    
    response = client.get_user_id(
        IdentityStoreId='string',
        AlternateIdentifier={
            'ExternalId': {
                'Issuer': 'string',
                'Id': 'string'
            },
            'UniqueAttribute': {
                'AttributePath': 'string',
                'AttributeValue': {...}|[...]|123|123.4|'string'|True|None
            }
        }
    )
    

    Although I personally found that the above method didn’t work for me due to it not being available in my installed version of Boto3, so I did this instead which worked perfectly –

    import boto3
    
    client = boto3.client('identitystore')
    
    response = client.list_users(
        IdentityStoreId='string',
        Filters=[
            {
                'AttributePath': 'UserName',
                'AttributeValue': 'string'
            },
        ]
    )
    
    print(response["Users"][0]["UserId"])
    

    Sources:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search