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



如何使用Boto3为AWS SSO用户获取UserId

我想用它来使用下面的代码为特定aws帐户的用户分配权限,然而,这需要PrincipalId,它是与每个用户相关的16-20位数字,在aws控制台中被称为User ID

你可以在这里阅读

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

如果您拥有要为其分配权限的用户的UserName,则可以通过编程方式使用IAM来确定该用户的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
)

您还需要使用"identitystore"来获取用户或组ID。试试这个从文档-

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

虽然我个人发现上面的方法不适用于我,因为它在我安装的Boto3版本中不可用,所以我做了这个,效果很好-

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

来源:

  • https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/identitystore.html#id24
  • https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/identitystore.html#IdentityStore.Client.get_user_id
  • https://botocore.amazonaws.com/v1/documentation/api/latest/reference/services/identitystore.html#IdentityStore.Client.list_users

最新更新