Skip to content

Instantly share code, notes, and snippets.

@marcogrcr
Created October 2, 2023 03:55
Show Gist options
  • Save marcogrcr/7bc493bd9155cae6f75b739c0643cd13 to your computer and use it in GitHub Desktop.
Save marcogrcr/7bc493bd9155cae6f75b739c0643cd13 to your computer and use it in GitHub Desktop.
Invokes AWS STS GetSessionToken using the AWS CLI and stores the temporary credentials in ~/.aws/credentials
#!/usr/bin/env python
import json, os, subprocess
from argparse import ArgumentParser
from configparser import ConfigParser
from pathlib import Path
# 1. parse args
parser = ArgumentParser(
prog='mfa-aws-credentials',
description='Invokes AWS STS GetSessionToken using the AWS CLI and stores the temporary credentials in ~/.aws/credentials'
)
parser.add_argument('-c', '--credentials-profile', help='The profile to use when invoking the AWS CLI')
parser.add_argument('-p', '--profile', required=True, help='The profile to store the temporary credentials under')
parser.add_argument('-s', '--serial-number', required=True, help='The AWS STS GetSessionToken\'s SerialNumber parameter')
parser.add_argument('-t', '--token-code', required=True, help='The AWS STS GetSessionToken\'s TokenCode parameter')
args = parser.parse_args()
# 2. get creds
aws_cmd = f'aws sts get-session-token --serial-number {args.serial_number} --token-code {args.token_code}'
if args.credentials_profile:
aws_cmd += f' --profile {args.credentials_profile}'
status, raw_res = subprocess.getstatusoutput(aws_cmd)
if status != 0:
print(raw_res)
exit(1)
creds = json.loads(raw_res).get('Credentials')
# 3. read ~/.aws/credentials
aws_creds_path = os.path.join(Path.home(), '.aws', 'credentials')
ini = ConfigParser()
ini.read(aws_creds_path)
# 4. update credentials
ini[args.profile] = {
'aws_access_key_id': creds.get('AccessKeyId'),
'aws_secret_access_key': creds.get('SecretAccessKey'),
'aws_session_token': creds.get('SessionToken')
}
# 5. write updated ~/.aws/credentials
with open(aws_creds_path, 'w') as f:
ini.write(f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment