简体   繁体   English

在 python 中使用 boto3 多次承担 IAM 角色

[英]assuming IAM role multiple times using boto3 in python

I'm new to working with aws and I'm not sure if I'm wording it correctly but basically, I need to sso in an account -> assume a role in account A -> then assume a role in account B. I am following this article ( https://medium.com/geekculture/programming-aws-iam-using-aws-python-sdk-boto3-part-4-62f2f1c21584 ) on how to assume the role.我是使用 aws 的新手,我不确定我的措辞是否正确,但基本上,我需要在一个帐户中进行 sso -> 在帐户 A 中扮演一个角色 -> 然后在帐户 B 中扮演一个角色。我我正在关注这篇文章 ( https://medium.com/geekculture/programming-aws-iam-using-aws-python-sdk-boto3-part-4-62f2f1c21584 ) 关于如何承担这个角色。 After I assume the first role in account A, I get the "iam_client" (from the article), then I don't know how can I assume the second role from account B.当我在账户A中担任第一个角色后,我得到了“iam_client”(来自文章),然后我不知道如何从账户B中担任第二个角色。

import boto3

from botocore.exceptions import ClientError从 botocore.exceptions 导入 ClientError

def lambda_handler(event, context): def lambda_handler(事件,上下文):

sts_client = boto3.client('sts')

try:
    response = sts_client.assume_role(
        RoleArn='arn:aws:iam::<TRUSTING_ACCOUNT_ID>:role/<ROLE_NAME_IN_TRUSTING_ACCOUNT>',
        RoleSessionName='assume_role_session'
    )
except ClientError as error:
    print('Unexpected error occurred... could not assume role', error)
    return error

try:
    iam_client = boto3.client('iam',
                              aws_access_key_id=response['Credentials']['AccessKeyId'],
                              aws_secret_access_key=response['Credentials']['SecretAccessKey'],
                              aws_session_token=response['Credentials']['SessionToken']
                              )
except ClientError as error:
    print('Unexpected error occurred... could not create iam client on trusting account', error)
    return error

EDIT: my aws accounts are setup in a way that I can't assume the role in account B right after sso login.编辑:我的 aws 帐户设置方式使我无法在 sso 登录后立即承担帐户 B 中的角色。 The trust relationship is setup in a way that it only allows a role in account A to assume it.信任关系的设置方式仅允许账户 A 中的角色代入该关系。

Check the AWS Official Code Library that contains this use case.查看包含此用例的AWS 官方代码库 When looking for an AWS code example, check this New AWS Doc.在查找 AWS 代码示例时,请查看此新 AWS 文档。

在此处输入图像描述

As you can see, the code library shows this use case in different supported programming langanges.如您所见,代码库以不同的受支持编程语言显示了此用例。 The topic is here:题目在这里:

Create an IAM user and assume a role with AWS STS using an AWS SDK 使用 AWS SDK 创建 IAM 用户并担任 AWS STS 的角色

You can assume roles by following the Python example.您可以按照 Python 示例代入角色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM