AWS:Boto3:AssumeRole示例,其中包括角色使用情况

时间:2017-05-25 03:34:15

标签: boto boto3

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

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

很好,我有assumeRoleObject。但现在我想用它来列出像ELB这样的东西,或者不是内置低级资源的东西。

如何做到这一点?如果我可能会问 - 请编写一个完整的例子,以便每个人都能受益。

9 个答案:

答案 0 :(得分:5)

您可以使用STS令牌承担角色,例如:

class Boto3STSService(object):
def __init__(self, arn):
    sess = Session(aws_access_key_id=ARN_ACCESS_KEY,
                   aws_secret_access_key=ARN_SECRET_KEY)
    sts_connection = sess.client('sts')
    assume_role_object = sts_connection.assume_role(RoleArn=arn, RoleSessionName=ARN_ROLE_SESSION_NAME,DurationSeconds=3600)
    self.credentials = assume_role_object['Credentials']

这将为您提供临时访问密钥和密钥,以及会话令牌。使用这些临时凭证,您可以访问任何服务。例如,如果要访问ELB,可以使用以下代码:

self.tmp_credentials = Boto3STSService(arn).credentials

def get_boto3_session(self):
        tmp_access_key = self.tmp_credentials['AccessKeyId']
        tmp_secret_key = self.tmp_credentials['SecretAccessKey']
        security_token = self.tmp_credentials['SessionToken']

    boto3_session = Session(
        aws_access_key_id=tmp_access_key,
        aws_secret_access_key=tmp_secret_key, aws_session_token=security_token
    )
    return boto3_session
def get_elb_boto3_connection(self, region):
    sess = self.get_boto3_session()
    elb_conn = sess.client(service_name='elb', region_name=region)
    return elb_conn

答案 1 :(得分:4)

参考 @jarrad 的解决方案,该解决方案在 2021 年 2 月不起作用,作为未明确使用 STS 的解决方案,请参阅以下内容


import boto3
import botocore.session
from botocore.credentials import AssumeRoleCredentialFetcher, DeferredRefreshableCredentials


def get_boto3_session(assume_role_arn=None):
    session = boto3.Session(aws_access_key_id="abc", aws_secret_access_key="def")
    if not assume_role_arn:
        return session

    fetcher = AssumeRoleCredentialFetcher(
        client_creator=_get_client_creator(session),
        source_credentials=session.get_credentials(),
        role_arn=assume_role_arn,
    )
    botocore_session = botocore.session.Session()
    botocore_session._credentials = DeferredRefreshableCredentials(
        method='assume-role',
        refresh_using=fetcher.fetch_credentials
    )

    return boto3.Session(botocore_session=botocore_session)


def _get_client_creator(session):
    def client_creator(service_name, **kwargs):
        return session.client(service_name, **kwargs)

    return client_creator

答案 2 :(得分:0)

如果您想要功能性的实现,这就是我所决定的:

persistent

答案 3 :(得分:0)

这是official AWS documentation的代码段,其中创建了s3资源以列出所有s3存储桶。 boto3的资源或其他服务的客户端可以以类似的方式构建。

# create an STS client object that represents a live connection to the 
# STS service
sts_client = boto3.client('sts')

# Call the assume_role method of the STSConnection object and pass the role
# ARN and a role session name.
assumed_role_object=sts_client.assume_role(
    RoleArn="arn:aws:iam::account-of-role-to-assume:role/name-of-role",
    RoleSessionName="AssumeRoleSession1"
)

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

# Use the temporary credentials that AssumeRole returns to make a 
# connection to Amazon S3  
s3_resource=boto3.resource(
    's3',
    aws_access_key_id=credentials['AccessKeyId'],
    aws_secret_access_key=credentials['SecretAccessKey'],
    aws_session_token=credentials['SessionToken'],
)

# Use the Amazon S3 resource object that is now configured with the 
# credentials to access your S3 buckets. 
for bucket in s3_resource.buckets.all():
    print(bucket.name)

答案 4 :(得分:0)

import json
import boto3


roleARN = 'arn:aws:iam::account-of-role-to-assume:role/name-of-role'
client = boto3.client('sts')
response = client.assume_role(RoleArn=roleARN, 
                              RoleSessionName='RoleSessionName', 
                              DurationSeconds=900)

dynamodb_client = boto3.client('dynamodb', region_name='us-east-1',
                    aws_access_key_id=response['Credentials']['AccessKeyId'],
                    aws_secret_access_key=response['Credentials']['SecretAccessKey'],
                    aws_session_token = response['Credentials']['SessionToken'])

response = dynamodb_client.get_item(
Key={
    'key1': {
        'S': '1',
    },
    'key2': {
        'S': '2',
    },
},
TableName='TestTable')
print(response)

答案 5 :(得分:0)

假设1)~/.aws/config~/.aws/credentials文件中填充了您希望担任的每个角色,并且2)默认角色的IAM策略中为每个角色定义了AssumeRole角色,那么您可以简单地(以伪代码)执行以下操作,而不必大惊小怪:

import boto3

# get all of the roles from the AWS config/credentials file using a config file parser
profiles = get_profiles()

for profile in profiles:

    # this is only used to fetch the available regions
    initial_session = boto3.Session(profile_name=profile)

    # get the regions
    regions = boto3.Session.get_available_regions('ec2')

    # cycle through the regions, setting up session, resource and client objects
    for region in regions:
        boto3_session = boto3.Session(profile_name=profile, region_name=region)
        boto3_resource = boto3_session.resource(service_name='s3', region_name=region)
        boto3_client = boto3_sessoin.client(service_name='s3', region_name=region)

        [ do something interesting with your session/resource/client here ]

答案 6 :(得分:0)

经过几天的搜索,这是我找到的最简单的解决方案。解释了here,但没有用法示例。

import boto3


for profile in boto3.Session().available_profiles:

    boto3.DEFAULT_SESSION = boto3.session.Session(profile_name=profile)

    s3 = boto3.resource('s3')

    for bucket in s3.buckets.all():
        print(bucket)

这将切换您将使用的默认角色。要不将配置文件设为默认配置文件,只需不将其分配给boto3.DEFAULT_SESSION。但是,请执行以下操作。

testing_profile = boto3.session.Session(profile_name='mainTesting')
s3 = testing_profile.resource('s3')

for bucket in s3.buckets.all():
    print(bucket)

重要的是,需要以特定方式设置.aws凭据。

[default]
aws_access_key_id = default_access_id
aws_secret_access_key = default_access_key

[main]
aws_access_key_id = main_profile_access_id
aws_secret_access_key = main_profile_access_key

[mainTesting]
source_profile = main
role_arn = Testing role arn
mfa_serial = mfa_arn_for_main_role

[mainProduction]
source_profile = main
role_arn = Production role arn
mfa_serial = mfa_arn_for_main_role

我不知道为什么,但是mfa_serial密钥必须在角色上起作用,而不是源帐户,这才有意义。

答案 7 :(得分:0)

#!/usr/bin/env python3

import boto3

sts_client = boto3.client('sts')
assumed_role = sts_client.assume_role(RoleArn =  "arn:aws:iam::123456789012:role/example_role",
                                      RoleSessionName = "AssumeRoleSession1",
                                      DurationSeconds = 1800)
session = boto3.Session(
    aws_access_key_id     = assumed_role['Credentials']['AccessKeyId'],
    aws_secret_access_key = assumed_role['Credentials']['SecretAccessKey'],
    aws_session_token     = assumed_role['Credentials']['SessionToken'],
    region_name           = 'us-west-1'
)

# now we make use of the role to retrieve a parameter from SSM
client = session.client('ssm')
response = client.get_parameter(
    Name = '/this/is/a/path/parameter',
    WithDecryption = True
)
print(response)

答案 8 :(得分:-1)

获取具有假定角色的会话:

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.

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

注意:我之前的回答是完全错误的,但是我无法将其删除,所以我用更好的工作答案取而代之。