Last active
September 19, 2019 23:00
-
-
Save gwsu2008/1fd537f024d5328cc10011da3c5473e6 to your computer and use it in GitHub Desktop.
iam_assume_role_1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import botocore | |
import boto3 | |
import datetime | |
from dateutil.tz import tzlocal | |
from botocore.credentials import DeferredRefreshableCredentials | |
from botocore.session import Session | |
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 = 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::*:role/*') | |
s3 = session.client('s3') # ... etc. | |
print(s3.list_buckets()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment