Skip to content

Instantly share code, notes, and snippets.

@MaxymVlasov
Last active July 4, 2019 07:28
Show Gist options
  • Save MaxymVlasov/92ebafdf430c379adeeda369a6368b9f to your computer and use it in GitHub Desktop.
Save MaxymVlasov/92ebafdf430c379adeeda369a6368b9f to your computer and use it in GitHub Desktop.
AWS CLI for IAM users with enabled MFA. Using without --profile option and without everyday useless repetition
[get-mfa]
aws_access_key_id = XXXXXXXXXXXXXXXXXXXX
aws_secret_access_key = XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
[default]
region = eu-west-1
output = json
mfa_serial = arn:aws:iam::xxxxxxxxxxxx:mfa/username
aws_access_key_id =
aws_secret_access_key =
aws_session_token =
[profile get-mfa]
region = eu-west-1
output = json
aws_mfa_func() {
# Params start #
MFA_CODE=$1
MFA_DEVICE_ARN=arn:aws:iam::xxxxxxxxxxxx:mfa/username
## Params end ##
CREDS=$(aws sts get-session-token --serial-number ${MFA_DEVICE_ARN} --token-code ${MFA_CODE} --profile get-mfa)
KEY=$(echo ${CREDS} | jq -r '.Credentials.AccessKeyId')
SECRET=$(echo ${CREDS} | jq -r '.Credentials.SecretAccessKey')
SESSION=$(echo ${CREDS} | jq -r '.Credentials.SessionToken')
sed -i 's|aws_access_key_id.*|aws_access_key_id = '${KEY}'|' ~/.aws/config
sed -i 's|aws_secret_access_key.*|aws_secret_access_key = '${SECRET}'|' ~/.aws/config
sed -i 's|aws_session_token.*|aws_session_token = '${SESSION}'|' ~/.aws/config
}
alias aws-mfa='aws_mfa_func'
alias am='aws_mfa_func'
$ aws-mfa 123456
$ aws s3 ls
2019-07-03 10:21:30 bucket1
2019-07-03 10:23:05 bucket2
2019-07-03 10:25:31 bucket3
$
$
$ am 654321
$ aws s3 ls
2019-07-03 10:21:30 bucket1
2019-07-03 10:23:05 bucket2
2019-07-03 10:25:31 bucket3
$
@SolDavidCloud
Copy link

Very nice, thanks for sharing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment