使用awscli,在/ / .aws / cli / cache中有一个凭证缓存,它允许我暂时缓存凭据。这在使用MFA时非常有用。 boto3是否具有类似功能,还是必须显式缓存从session = boto3.session.Session(profile_name='CTO:Admin')
返回的凭据?
答案 0 :(得分:5)
它已经存在。
http://boto3.readthedocs.org/en/latest/guide/configuration.html#assume-role-provider
当您指定具有IAM角色配置的配置文件时,boto3将进行AssumeRole调用以检索临时凭证。随后的boto3 API调用将使用缓存的临时凭证,直到它们过期,在这种情况下,boto3将自动刷新凭据。 boto3不会将这些临时凭证写入磁盘。这意味着来自AssumeRole调用的临时凭证仅在单个会话中缓存在内存中。从该会话创建的所有客户端将共享相同的临时凭证。
答案 1 :(得分:2)
总结以上几点,一个工作实例:
from os import path
import os
import sys
import json
import datetime
from distutils.spawn import find_executable
from botocore.exceptions import ProfileNotFound
import boto3
import botocore
def json_encoder(obj):
"""JSON encoder that formats datetimes as ISO8601 format."""
if isinstance(obj, datetime.datetime):
return obj.isoformat()
else:
return obj
class JSONFileCache(object):
"""JSON file cache.
This provides a dict like interface that stores JSON serializable
objects.
The objects are serialized to JSON and stored in a file. These
values can be retrieved at a later time.
"""
CACHE_DIR = path.expanduser(path.join('~', '.aws', 'ansible-ec2', 'cache'))
def __init__(self, working_dir=CACHE_DIR):
self._working_dir = working_dir
def __contains__(self, cache_key):
actual_key = self._convert_cache_key(cache_key)
return path.isfile(actual_key)
def __getitem__(self, cache_key):
"""Retrieve value from a cache key."""
actual_key = self._convert_cache_key(cache_key)
try:
with open(actual_key) as f:
return json.load(f)
except (OSError, ValueError, IOError):
raise KeyError(cache_key)
def __setitem__(self, cache_key, value):
full_key = self._convert_cache_key(cache_key)
try:
file_content = json.dumps(value, default=json_encoder)
except (TypeError, ValueError):
raise ValueError("Value cannot be cached, must be "
"JSON serializable: %s" % value)
if not path.isdir(self._working_dir):
os.makedirs(self._working_dir)
with os.fdopen(os.open(full_key,
os.O_WRONLY | os.O_CREAT, 0o600), 'w') as f:
f.truncate()
f.write(file_content)
def _convert_cache_key(self, cache_key):
full_path = path.join(self._working_dir, cache_key + '.json')
return full_path
session = boto3.session.Session()
try:
cred_chain = session._session.get_component('credential_provider')
except ProfileNotFound:
print "Invalid Profile"
sys.exit(1)
provider = cred_chain.get_provider('assume-role')
provider.cache = JSONFileCache()
# Do something with the session...
ec2 = session.resource('ec2')
答案 2 :(得分:1)
我创建了一个为您提供此功能的Python库 - 请参阅https://github.com/mixja/boto3-session-cache
示例:
import boto3_session_cache
# This returns a regular boto3 client object with the underlying session configured with local credential cache
client = boto3_session_cache.client('ecs')
ecs_clusters = client.list_clusters()
答案 3 :(得分:0)
最初,凭证缓存和自动续订临时凭证是AWSCLI的一部分,但this commit(以及后续的一些)将该功能移至botocore,这意味着它现在也可以在boto3中使用。