Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用Boto3以编程方式获取IAM用户的用户ID_Python_Amazon Web Services_Boto3_Amazon Iam - Fatal编程技术网

Python 使用Boto3以编程方式获取IAM用户的用户ID

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

我试图在创建用户后获取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 = 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主体的标识。它只提供与您在呼叫时隐式使用的凭据相关联的标识