-
-
Save ashishjullia/c188cdf6107d0b348e9baa8f01ca6919 to your computer and use it in GitHub Desktop.
aws-cli MFA access via assume role
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
#!/bin/bash | |
if [ "$1" == "" ]; then | |
echo "Usage: $(basename "$0") <MFA-TOKEN>" | |
exit 1 | |
fi | |
session_duration=129600 # 36 hours | |
mfa_device_code=$(aws iam list-mfa-devices | jq -r .MFADevices[0].SerialNumber) | |
if [ -z "$mfa_device_code" ]; then | |
echo "Failed to retrieve MFA device code. Make sure you have configured your AWS CLI correctly." | |
exit 1 | |
fi | |
mfa_code=$1 | |
tmp_creds_file="$HOME/.aws/tempcreds" | |
aws_creds_file="$HOME/.aws/credentials" | |
orig_creds_file="$HOME/.aws/origcreds" | |
if [ ! -f "$orig_creds_file" ]; then | |
echo "Original credentials file not found at $orig_creds_file" | |
echo "Backing up current credentials to $orig_creds_file" | |
cp $aws_creds_file $orig_creds_file | |
fi | |
cp $orig_creds_file $aws_creds_file | |
cmd="aws sts get-session-token --duration-seconds ${session_duration} --serial-number ${mfa_device_code} --token-code ${mfa_code}" | |
echo "$cmd" | |
$cmd > ${tmp_creds_file} | |
new_creds=$(cat ${tmp_creds_file}) | |
if [ -z "$new_creds" ]; then | |
echo "Request failed" | |
exit 1 | |
fi | |
access_key_id=$(echo ${new_creds} | jq -r ".Credentials.AccessKeyId") | |
secret_access_key=$(echo ${new_creds} | jq -r ".Credentials.SecretAccessKey") | |
session_token=$(echo ${new_creds} | jq -r ".Credentials.SessionToken") | |
expiry=$(echo ${new_creds} | jq -r ".Credentials.Expiration") | |
printf "[default]\naws_access_key_id = ${access_key_id}\naws_secret_access_key = ${secret_access_key}\naws_session_token = ${session_token}" > ${aws_creds_file} | |
# Export the new environment variables | |
export AWS_ACCESS_KEY_ID=${access_key_id} | |
export AWS_SECRET_ACCESS_KEY=${secret_access_key} | |
export AWS_SESSION_TOKEN=${session_token} | |
echo "All set. Expiry at: $(date -d ${expiry})" | |
echo "AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID}" | |
echo "AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY}" | |
echo "AWS_SESSION_TOKEN=${AWS_SESSION_TOKEN}" | |
echo "Contents of ${aws_creds_file}:" | |
cat ${aws_creds_file} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's what I came up with for Windows powershell:
This allows a user to run it whenever they want - it will overwrite the existing temporary access codes if they exist, and generate new ones if they don't.
Also allows mfa codes with 0's at the front