You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Boto3查询AWS SSO用户的UserId

如何通过Boto3获取AWS SSO用户的UserId?

你需要调用AWS SSO Admin的create_account_assignment接口为特定AWS账户用户分配权限,该接口要求传入的PrincipalId即控制台显示的16-20位数字User ID。以下是通过Boto3获取该ID的方法:

核心思路

AWS SSO用户的信息存储在Identity Store中,需通过boto3的identitystore客户端来查询用户ID。

步骤1:获取Identity Store ID

首先需要关联你的SSO实例ARN与对应的Identity Store ID,可通过SSO Admin客户端的describe_instance接口获取:

import boto3

# 初始化SSO Admin客户端
sso_admin_client = boto3.client('sso-admin')

# 替换为你的SSO实例ARN
instance_arn = 'arn:aws:sso:::instance/ssoins-xxxxxxxxx'

# 查询实例信息,获取Identity Store ID
response = sso_admin_client.describe_instance(InstanceArn=instance_arn)
identity_store_id = response['Instance']['IdentityStoreId']

步骤2:查询用户的UserId

使用Identity Store客户端,通过用户名或其他属性查询用户详情,提取UserId字段:

方式一:通过用户名查询单个用户

# 初始化Identity Store客户端
identity_store_client = boto3.client('identitystore')

# 替换为目标用户名
username = 'target-user'

# 查询用户信息
response = identity_store_client.list_users(
    IdentityStoreId=identity_store_id,
    Filters=[
        {
            'AttributePath': 'UserName',
            'AttributeValue': username
        }
    ]
)

# 提取UserId(若存在匹配用户)
if response['Users']:
    user_id = response['Users'][0]['UserId']
    print(f"用户{username}的UserId为:{user_id}")
else:
    print("未找到匹配的用户")

方式二:获取所有用户列表

如果需要批量获取用户信息,可直接调用list_users不带筛选条件:

response = identity_store_client.list_users(IdentityStoreId=identity_store_id)
for user in response['Users']:
    print(f"用户名:{user['UserName']},UserId:{user['UserId']}")

# 处理分页(若用户数量超过默认返回上限)
while 'NextToken' in response:
    response = identity_store_client.list_users(
        IdentityStoreId=identity_store_id,
        NextToken=response['NextToken']
    )
    for user in response['Users']:
        print(f"用户名:{user['UserName']},UserId:{user['UserId']}")

注意事项

  • 确保你的AWS凭证拥有sso-admin:DescribeInstance和identitystore:ListUsers的权限
  • UserId字段的值就是create_account_assignment接口所需的PrincipalId

内容的提问来源于stack exchange,提问作者Ranopriyo Neogy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 03:25:49