Last active
November 28, 2020 18:49
-
-
Save DaytonG/b476b2864aac84914af7faa69b7b34d2 to your computer and use it in GitHub Desktop.
Create a new token auth AWS session using an MFA device
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
#!/bin/env python3 | |
""" | |
Create a new token auth AWS session using an MFA device. | |
Usage: | |
$(python3 awsmfa.py 123456) | |
You can also install this into your shell profile, like ~/.bashrc | |
``` | |
setawsmfa() { | |
eval $(python3 ~/bin/awsmfa.py $1) | |
} | |
``` | |
Then usage becomes `setawsmfa 123456` | |
""" | |
import os | |
import sys | |
import subprocess | |
import json | |
# Set your MFA device | |
mfa_arn = "arn:aws:iam::..." | |
def maybeUnsetEnv(key): | |
try: | |
del os.environ[key] | |
except KeyError: | |
pass | |
def set_env(mfaDeviceToken): | |
args = [ | |
"aws", "sts", "get-session-token", | |
"--serial-number", mfa_arn, | |
"--token-code", mfaDeviceToken | |
] | |
maybeUnsetEnv('AWS_ACCESS_KEY_ID') | |
maybeUnsetEnv('AWS_SECRET_ACCESS_KEY') | |
maybeUnsetEnv('AWS_SESSION_TOKEN ') | |
cmd = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True) | |
creds = json.loads(cmd.stdout)['Credentials'] | |
print('export AWS_ACCESS_KEY_ID=' + creds['AccessKeyId']) | |
print('export AWS_SECRET_ACCESS_KEY=' + creds['SecretAccessKey']) | |
print('export AWS_SESSION_TOKEN=' + creds['SessionToken']) | |
if __name__ == "__main__": | |
set_env(sys.argv[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment