Skip to content

Instantly share code, notes, and snippets.

@HarlemSquirrel
Created June 8, 2021 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HarlemSquirrel/55bf904642df8ff76472e04793905979 to your computer and use it in GitHub Desktop.
Save HarlemSquirrel/55bf904642df8ff76472e04793905979 to your computer and use it in GitHub Desktop.
Refresh AWS MFA credentials
#! /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