Created
June 8, 2021 16:04
-
-
Save HarlemSquirrel/55bf904642df8ff76472e04793905979 to your computer and use it in GitHub Desktop.
Refresh AWS MFA credentials
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
| #! /usr/bin/env ruby | |
| ## | |
| # Retrieve MFA credentials using the default profile and saving them to the mfa profile. | |
| # Old credentials are removed in this process. | |
| # | |
| require 'json' | |
| AWS_CREDS_FILE_PATH = File.join(ENV['HOME'], '.aws/credentials') | |
| mfa_devices = `AWS_PROFILE=default aws iam list-mfa-devices` | |
| device_serial_number = JSON.parse(mfa_devices)['MFADevices'][0]['SerialNumber'] | |
| print "MFA code: " | |
| token_code = STDIN.gets.chomp | |
| # puts token_code | |
| raw_creds = `AWS_PROFILE=default aws sts get-session-token --duration-seconds 129600 --serial-number #{device_serial_number} --token-code #{token_code}` | |
| creds = JSON.parse(raw_creds)['Credentials'] | |
| formatted_creds = "aws_access_key_id = #{creds['AccessKeyId']}\n" \ | |
| "aws_secret_access_key = #{creds['SecretAccessKey']}\n" \ | |
| "aws_session_token = #{creds['SessionToken']}\n" | |
| current_creds_file_content = File.read(AWS_CREDS_FILE_PATH) | |
| new_creds_file_content = current_creds_file_content.gsub(/(?<=\[mfa\]\n)([^\n]+\n){3}/, formatted_creds) | |
| puts raw_creds | |
| puts "==> New Credentials File with Expiration: #{creds['Expiration']}\n\n", | |
| new_creds_file_content | |
| File.write(AWS_CREDS_FILE_PATH, new_creds_file_content) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment