gpt4 book ai didi

boto - AWS : Boto3: AssumeRole example which includes role usage

转载 作者:行者123 更新时间:2023-12-04 02:09:07 30 4
gpt4 key购买 nike

我试图以这样一种方式使用 AssumeRole,以便我遍历多个帐户并检索这些帐户的 Assets 。我已经做到了这一点:

import boto3
stsclient = boto3.client('sts')

assumedRoleObject = sts_client.assume_role(
RoleArn="arn:aws:iam::account-of-role-to-assume:role/name-of-role",
RoleSessionName="AssumeRoleSession1")

太好了,我有假定的角色对象。但是现在我想用它来列出诸如 ELB 之类的东西或不是内置低级资源的东西。

怎么做呢?如果我可以问 - 请编写一个完整的示例,以便每个人都可以受益。

最佳答案

要获取具有假定角色的 session :

import botocore
import boto3
import datetime
from dateutil.tz import tzlocal

assume_role_cache: dict = {}
def assumed_role_session(role_arn: str, base_session: botocore.session.Session = None):
base_session = base_session or boto3.session.Session()._session
fetcher = botocore.credentials.AssumeRoleCredentialFetcher(
client_creator = base_session.create_client,
source_credentials = base_session.get_credentials(),
role_arn = role_arn,
extra_args = {
# 'RoleSessionName': None # set this if you want something non-default
}
)
creds = botocore.credentials.DeferredRefreshableCredentials(
method = 'assume-role',
refresh_using = fetcher.fetch_credentials,
time_fetcher = lambda: datetime.datetime.now(tzlocal())
)
botocore_session = botocore.session.Session()
botocore_session._credentials = creds
return boto3.Session(botocore_session = botocore_session)

# usage:
session = assumed_role_session('arn:aws:iam::ACCOUNTID:role/ROLE_NAME')
ec2 = session.client('ec2') # ... etc.

结果 session 的凭据将在需要时自动刷新,这非常好。

注意:我之前的答案是完全错误的,但我无法删除它,所以我用更好且有效的答案替换了它。

关于boto - AWS : Boto3: AssumeRole example which includes role usage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44171849/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com