Last active
June 26, 2017 16:46
-
-
Save daidokoro/44255154d2c032ed69796d3565f10171 to your computer and use it in GitHub Desktop.
MFA Session Token
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
from boto3 import Session | |
from sys import argv | |
from os import unlink, path | |
serial = "arn:aws:iam::<Account Number>:mfa/<Username>" | |
profile = "<your aws config source profile here>" | |
credfile = os.path.join(os.getenv("HOME"), ".aws/credentials") | |
def set_creds(token): | |
sess = Session(profile_name=profile) | |
sts = sess.client('sts') | |
resp = sts.get_session_token( | |
DurationSeconds=28800, | |
SerialNumber=serial, | |
TokenCode=token | |
)['Credentials'] | |
# build credentials string | |
creds = "[%s]" % profile | |
creds += "\nregion = eu-west-1" | |
creds += "\naws_secret_access_key = %s" % resp["SecretAccessKey"] | |
creds += "\naws_access_key_id = %s" % resp["AccessKeyId"] | |
creds += "\naws_session_token = %s\n" % resp["SessionToken"] | |
# write creds file | |
with open(credfile, "w") as f: | |
f.write(creds) | |
return creds | |
if __name__ == '__main__': | |
try: | |
print("INFO: Removing: %s\n" % credfile) | |
if path.exists(credfile): unlink(credfile) | |
print(set_creds(argv[1])) | |
print("INFO: .aws/crendentials written..") | |
except Exception as e: | |
print(e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment