Skip to content

Instantly share code, notes, and snippets.

@StuMason
Created May 6, 2022 11:04
Show Gist options
  • Save StuMason/1c2e67c6dae079c0ed8321720c4d87e1 to your computer and use it in GitHub Desktop.
Save StuMason/1c2e67c6dae079c0ed8321720c4d87e1 to your computer and use it in GitHub Desktop.
AWS MFA switching
"""
Switching between accounts where MFA is required can be a little manually intensive.
This script updates a temporary profile with a key, secret and session token (using a more stable profile - in this case 'default').
You can then use this temporary profile to switch between accounts.
i.e I have my main profile
I created a `[mfa_temp_session]` profile in my credentials which looked like this:
[mfa_temp_session]
output = json
region = eu-west-1
aws_access_key_id = the_script_will_auto_populate_once_ran
aws_secret_access_key = the_script_will_auto_populate_once_ran
aws_session_token = the_script_will_auto_populate_once_ran
and I have in my config file a couple of stanzas like this:
```
[profile sandbox]
role_arn = arn:aws:iam::123456789011:role/CloudDeveloperRole
source_profile = mfa_temp_session
[profile staging]
role_arn = arn:aws:iam::123456789011:role/CloudDeveloperRole
source_profile = mfa_temp_session
```
I then run this file with `python ~/aws_mfa.py -c 123456`
Once run, I know have my session token using my MFA device, so I can then use my other roles, like this:
`aws sts get-caller-identity --profile staging`
"""
import boto3
import argparse
THE_PROFILE_WITH_MFA_PROTECTION='default'
MDA_DEVICE_SERIAL_NUMBER='arn:aws:iam::***********:mfa/{Your username}'
CREDENTIALS_FILE_LOCATION = '/Users/USERNAME/.aws/credentials'
def signin(code):
session = boto3.session.Session(profile_name=THE_PROFILE_WITH_MFA_PROTECTION)
client = session.client('sts')
response = client.get_session_token(
DurationSeconds=3600,
SerialNumber=MDA_DEVICE_SERIAL_NUMBER,
TokenCode=code
)
with open(CREDENTIALS_FILE_LOCATION, 'r') as read_file:
credents_array = read_file.readlines()
nmfa_index = credents_array.index('[mfa_temp_session]\n')
credents_array[nmfa_index + 1] = f'output = json\n'
credents_array[nmfa_index + 2] = f'region = eu-west-1\n'
credents_array[nmfa_index + 3] = f'aws_access_key_id = {response["Credentials"]["AccessKeyId"]}\n'
credents_array[nmfa_index + 4] = f'aws_secret_access_key = {response["Credentials"]["SecretAccessKey"]}\n'
credents_array[nmfa_index + 5] = f'aws_session_token = {response["Credentials"]["SessionToken"]}\n'
with open(CREDENTIALS_FILE_LOCATION, 'w') as write_file:
write_file.writelines(credents_array)
write_file.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--code', type=str, required=True)
args = parser.parse_args()
signin(args.code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment