Boto3:动态获取凭据?

Boto3: get credentials dynamically?

我正在努力寻找如何从我的代码中动态获取 aws_access_key_id 和 aws_secret_access_key。

在 boto2 中我可以执行以下操作:boto.config.get_value('Credentials', 'aws_secret_access_key') 但我似乎无法在 boto3 中找到类似的方法。如果我查看 boto3.Session()._session._credentials,我就能找到钥匙,但这对我来说似乎是所有黑客之母,我宁愿不走那条路。

通常最好只 use temporary credentials. You can get temporary credentials with STS.get_session_token

编辑:从 this PR 开始,您可以像这样访问当前会话凭据:

import boto3

session = boto3.Session()
credentials = session.get_credentials()

# Credentials are refreshable, so accessing your access key / secret key
# separately can lead to a race condition. Use this to get an actual matched
# set.
credentials = credentials.get_frozen_credentials()
access_key = credentials.access_key
secret_key = credentials.secret_key

redshift = session.client('redshift')
...

我仍然建议使用范围完全符合 redshift 需要的临时凭证。

使用botocore

>>> import botocore.session
>>> session = botocore.session.get_session()

>>> session.get_credentials().access_key
'AKIAABCDEF6RWSGI234Q'

>>> session.get_credentials().secret_key
'abcdefghijkl+123456789+qbcd'

>>> session.get_config_variable('region')
'us-east-1'

我能否建议使用 boto3 访问密钥是错误的:

import boto3
session = boto3.Session(profile_name="my-profile")

dynamodb = session.resource(
    "dynamodb",
    region_name=session.region_name,
    # aws_access_key_id=session.get_credentials().access_key,
    # aws_secret_access_key=session.get_credentials().secret_key,
)

注意,我注释掉了访问密钥,因为 1:

Any clients created from this session will use credentials from the [my-profile] section of ~/.aws/credentials.