python-3.x - Boto3 担任 MFA 的跨账户角色
问题描述
使用 python3 和 boto3 如何在需要启用多重身份验证 (MFA) 的不同 AWS 账户中担任角色?
寻找代码示例。本网站上的类似问题涉及除 boto3 以外的技术或不包括 MFA 要求。
解决方案
使用 boto3,您需要允许用户在切换角色之前输入 MFA 令牌。下面的代码显示了切换到角色以列出不同账户中的存储桶的示例。重要的一点是在调用中添加SerialNumber
和TokenCode
选项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'])
我希望这对未来的搜索者有参考价值。
推荐阅读
- python - 如何使用 OpenCV + Python 检测 QR 码角标记(仅)?
- azure - MS Graph Daemon App - 获取承载令牌
- r - 在R中使用带有自定义函数的apply删除for循环
- django-rest-framework - 使用相同查找应用多个值时如何执行“或”?
- select - 过滤依赖于另一个值的值
- c# - 向 webservice 传递参数并接收值
- highcharts - 可以像这样设置 HIGHCHARTS 样式吗?
- go - 为什么比赛检测器在这里报告比赛条件?
- azure - 在 Azure 上发布特定的 appsettings.json 文件
- reactjs - React 似乎在修改变量名,然后抱怨它们不存在