首页 > 解决方案 > Boto3 担任 MFA 的跨账户角色

问题描述

使用 python3 和 boto3 如何在需要启用多重身份验证 (MFA) 的不同 AWS 账户中担任角色?

寻找代码示例。本网站上的类似问题涉及除 boto3 以外的技术或不包括 MFA 要求。

标签: python-3.xamazon-web-servicesboto3amazon-iammulti-factor-authentication

解决方案


使用 boto3,您需要允许用户在切换角色之前输入 MFA 令牌。下面的代码显示了切换到角色以列出不同账户中的存储桶的示例。重要的一点是在调用中添加SerialNumberTokenCode选项sts_client.assume_role()

然后可以将返回的凭据与另一个 boto3 客户端一起使用以执行一些实际工作,在这种情况下,列出目标帐户中的 s3 存储桶。

#!/usr/bin/env python
import boto3

sts_client = boto3.client('sts')

def assume_role_with_mfa(role_arn):

    '''
        Assume cross account role with MFA and return credentials
    '''

    mfa_otp = input("Enter the MFA code: ")

    assumedRoleObject = sts_client.assume_role(
        RoleArn=role_arn,
        RoleSessionName='mysession',
        SerialNumber="arn:aws:iam::987654321098:mfa/my_userid",
        DurationSeconds=3600,
        TokenCode=mfa_otp
    )

    # From the response that contains the assumed role, get the temporary
    # credentials that can be used to make subsequent API calls
    return assumedRoleObject['Credentials']


# Get the cross-account credentials, then use them to create 
# an S3 Client and list buckets in the account

creds = assume_role_with_mfa("arn:aws:iam::123456789012:role/myrole")

s3_client = boto3.client(service_name="s3",
            aws_access_key_id=creds['AccessKeyId'],
            aws_secret_access_key=creds['SecretAccessKey'],
            aws_session_token=creds['SessionToken'])
        
buckets = s3_client.list_buckets()
for bucket in buckets['Buckets']:
    print(bucket['Name'])

我希望这对未来的搜索者有参考价值。


推荐阅读