Python 使用Boto3以编程方式获取IAM用户的用户ID
我试图在创建用户后获取UserId,使用“account\u id=boto3.client('sts').get\u caller\u identity().get('some\u other\u user')”,但对于输出,我没有得到,原因可能是什么。我对boto和python非常陌生,所以它可能很小Python 使用Boto3以编程方式获取IAM用户的用户ID,python,amazon-web-services,boto3,amazon-iam,Python,Amazon Web Services,Boto3,Amazon Iam,我试图在创建用户后获取UserId,使用“account\u id=boto3.client('sts').get\u caller\u identity().get('some\u other\u user')”,但对于输出,我没有得到,原因可能是什么。我对boto和python非常陌生,所以它可能很小 import boto3 import sys import json iam = boto3.resource('iam') #resource representing IAM group
import boto3
import sys
import json
iam = boto3.resource('iam') #resource representing IAM
group = iam.Group('group1') # Name of group
created_user = iam.create_user(
UserName='some_other_user'
)
account_id = boto3.client('sts').get_caller_identity().get('some_other_user')
print(account_id)
create_group_response = iam.create_group(GroupName = 'group1')
response = group.add_user(
UserName='some_other_user' #name of user
)
group = iam.Group('group1')
response = group.attach_policy(
PolicyArn='arn:aws:iam::196687784:policy/boto-test'
)
该函数返回一个dict,其中包含:
{
'UserId': 'AIDAEXAMPLEHERE',
'Account': '123456789012',
'Arn': 'arn:aws:iam::123456789012:user/james'
}
因此,要使用这个:
import boto3
sts = boto3.client('sts')
response = sts.get_caller_identity()
print('User ID:', response['UserId'])
或者您可以使用response.get('UserId')
来获取用户ID。响应字典中用户ID的键始终是文本UserId
。它没有变化(例如,您不能调用response.get('james')
)
无法使用sts.get\u caller\u identity()
检索任意IAM主体的标识。它只提供与您在呼叫时隐式使用的凭据相关联的标识