2016-03-08 10 views
6

awscliには〜/ .aws/cli/cacheに資格キャッシュがあり、しばらくの間資格情報をキャッシュできます。これは、MFAを使用する場合に非常に役立ちます。 boto3にも同様の機能がありますか、またはsession = boto3.session.Session(profile_name='CTO:Admin')から返された認証情報を明示的にキャッシュする必要がありますか?boto3にはawscliに匹敵する資格キャッシュがありますか?

+0

あなたはこれを理解することができましたか? – KunalC

答えて

0

元々、資格情報のキャッシングと自動更新はAWSCLIの一部でしたが、this commit(およびその後のもの)はその機能をbotocoreに移しました。つまり、boto3で利用できるようになりました。

+1

〜/ .aws/cli/cacheファイルを実際に共有する方法はありますか?より良い方法が見つからない場合は、awscli/customizations/assumerole.pyのJSONFileCacheをコピーしてValueErrorを取得しました。値をキャッシュできません。JSONをシリアライズ可能でなければなりません。 "json.dumpsを使いました。このシリアライゼーションの独自のバージョンを取り上げることができますが、私は何かが分からないと思っています。ありがとう – n2ygk

+1

'datetime.datetime'のカスタムjsonエンコーディングを追加する必要があります。 [awscli/utils.py](https://github.com/aws/aws-cli/blob/3db7be30dfdd76f4e322b83b67af3134ae0b32ac/awscli/utils.py#L129)、デフォルトエンコーダ 'json.dumps(value、default = json_encoder) '。 –

3

すでにあります。

http://boto3.readthedocs.org/en/latest/guide/configuration.html#assume-role-provider

When you specify a profile that has IAM role configuration, boto3 will make an AssumeRole call to retrieve temporary credentials. Subsequent boto3 API calls will use the cached temporary credentials until they expire, in which case boto3 will automatically refresh credentials. boto3 does not write these temporary credentials to disk. This means that temporary credentials from the AssumeRole calls are only cached in memory within a single Session. All clients created from that session will share the same temporary credentials.

+2

.aws/credentialsと.aws/configファイルが使用されますが、**。aws/cli/cache **は使用されません。すべてのキャッシュはメモリ内のみであるため、Pythonスクリプトの実行中のみ存在しますawscliのJSONFileCacheで実装されている永続的なキャッシュはありません。 – n2ygk

2

、実施例上記の点を要約すると:私はあなたのためにこれを提供してPythonライブラリを作成し

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') 
1

を - 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() 
関連する問題