forked from pokey/dotfiles
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathawsmfa
executable file
·52 lines (43 loc) · 1.79 KB
/
awsmfa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/env bash
# Init pyenv and activate awscli virtualenv
# NB: These steps must occur before the pipefail step below due to a bug in pip
if which pyenv > /dev/null; then eval "$(pyenv init -)"; fi
pyenv activate awscli
set -euo pipefail
IFS=$'\n\t'
# Based on https://github.com/lokori/secretman/blob/580c2556ad54ec6f22da854f852f2de775a9e150/awsenv.sh
# This script is designed so that the output is to be evaled, ie
#
# eval $(awsmfa <ROLE>)
#
# where <ROLE> is the name of an aws role. It assumes that you have ykman
# installed, and that you have configured it to have an oath code, ie
#
# ykman oath add -t aws-<ACCOUNT_NUMBER>-<IAM_USERNAME>
#
# Also assumes that your defaut user has privileges to assume the given role.
#
# XXX Disabled ykman because it isn't working on MacOS
if [[ $# -ge 1 ]]; then
ROLE="$1"
else
(>&2 echo "ERROR: Please provide aws profile as argument.")
exit -1
fi
CALLER_IDENTITY=($(aws sts get-caller-identity --output text))
AWS_ACCOUNT_NUMBER="${CALLER_IDENTITY[0]}"
AWS_IAM_USER_ARN="${CALLER_IDENTITY[1]}"
AWS_IAM_USERNAME="$(basename "$AWS_IAM_USER_ARN")"
MFA_SERIAL="arn:aws:iam::$AWS_ACCOUNT_NUMBER:mfa/$AWS_IAM_USERNAME"
# TOKEN_CODE=$(ykman oath code -s "aws-$AWS_ACCOUNT_NUMBER-$AWS_IAM_USERNAME")
read -p 'Enter MFA code: ' TOKEN_CODE
PROFILE_INFO=($(aws sts assume-role \
--role-arn "arn:aws:iam::$AWS_ACCOUNT_NUMBER:role/$ROLE" \
--serial-number "$MFA_SERIAL" \
--role-session-name "$AWS_IAM_USERNAME" \
--token-code "$TOKEN_CODE" \
--query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' \
--output text))
echo export AWS_ACCESS_KEY_ID="${PROFILE_INFO[0]}" \
AWS_SECRET_ACCESS_KEY="${PROFILE_INFO[1]}" \
AWS_SESSION_TOKEN="${PROFILE_INFO[2]}"