本文介绍了AWS:Boto3:AssumeRole示例,其中包括角色用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以一种方式使用AssumeRole,即我遍历多个帐户并检索那些帐户的资产.我已经做到了这一点:

I'm trying to use the AssumeRole in such a way that i'm traversing multiple accounts and retrieving assets for those accounts. I've made it to this point:

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")

太好了,我有前提RoleObject.但是现在我想用它来列出诸如ELB之类的东西,或者不是内置的低级资源的东西.

Great, i have the assumedRoleObject. But now i want to use that to list things like ELBs or something that isn't a built-in low level resource.

如何做到这一点?如果我可能要问-请写出完整的示例,以便每个人都可以受益.

How does one go about doing that? If i may ask - please code out a full example, so that everyone can benefit.

推荐答案

要获得具有假定角色的会话,请执行以下操作:

To get a session with an assumed role:

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.

生成的会话凭据将在需要时自动刷新,这非常好.

The resulting session's credentials will be automatically refreshed when required which is quite nice.

注意:我之前的答案是完全错误的,但是我无法删除它,因此我将其替换为一个更好且可行的答案.

Note: my previous answer was outright wrong but I can't delete it, so I've replaced it with a better and working answer.

这篇关于AWS:Boto3:AssumeRole示例,其中包括角色用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-10 07:42