Created
October 15, 2020 23:55
-
-
Save yarick/64c9881a191cbd27118aa8881c91499e to your computer and use it in GitHub Desktop.
Update my aws credentials with token using my MFA Code and save as local aws credentials
This file contains 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
#!/usr/bin/env python3 | |
### #!/usr/bin/python3 | |
import sys | |
from pprint import pprint | |
import subprocess | |
# stdoutdata = subprocess.getoutput("cat /root/.aws/credentials") | |
# print("stdoutdata: " + stdoutdata.split()[0]) | |
MY_USER_ID="yarick" | |
MY_MFA_ID='0123456789' | |
my_token = sys.argv[1] | |
my_command = 'aws sts get-session-token --profile mfa --serial-number arn:aws:iam::' + MY_MFA_ID + ':mfa/' + MY_USER_ID + ' --token-code ' + my_token | |
stdoutdata = subprocess.getoutput(my_command) | |
print('-----------') | |
print(my_command) | |
print('-----------') | |
pprint(stdoutdata) | |
for line in stdoutdata.split('\n'): | |
if 'AccessKeyId' in line: aws_access_key_id = line.split('"')[3] | |
if 'SessionToken' in line: aws_session_token = line.split('"')[3] | |
if 'SecretAccessKey' in line: aws_secret_access_key = line.split('"')[3] | |
print('-----------') | |
print(aws_access_key_id) | |
print(aws_secret_access_key) | |
print(aws_session_token) | |
#aws_access_key_id = 'aws_access_key_id' | |
#aws_secret_access_key = 'aws_secret_access_key' | |
#aws_session_token = 'aws_session_token' | |
print() | |
print() | |
in_file = open("/root/.aws/credentials", "rt", encoding="us-ascii") # open file lorem.txt for reading text data | |
contents = in_file.read() # read the entire file into a string variable | |
in_file.close() # close the file | |
print('Existing Creds') | |
pprint(contents) # print contents | |
print() | |
print() | |
print() | |
out_contents = '' | |
for line in contents.split('\n'): | |
if '#' not in line: | |
if '[default]' in line: | |
is_default = True | |
if '[' in line and not '[default]' in line: | |
is_default = False | |
if is_default: | |
if 'aws_access_key_id' in line: line = 'aws_access_key_id = ' + aws_access_key_id | |
if 'aws_secret_access_key' in line: line = 'aws_secret_access_key = ' + aws_secret_access_key | |
if 'aws_session_token' in line: line = 'aws_session_token = ' + aws_session_token | |
out_contents = out_contents + line + '\n' | |
print('New Creds') | |
pprint(out_contents) | |
with open("/root/.aws/credentials", "wt", ) as oh: | |
oh.write(out_contents) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment