Last active
June 16, 2023 02:19
-
-
Save hayajo/f97ebe0fc0cd26d4d7e7403281787aee to your computer and use it in GitHub Desktop.
AWS CLI で MFA するスクリプト
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 bash | |
MFA_PROFILE_SUFFIX="-mfa" | |
AWS_PROFILE="$(aws configure list-profiles | grep -v -e "$MFA_PROFILE_SUFFIX\$" | fzf)" | |
if [ -z "$AWS_PROFILE" ]; then | |
echo "Please select profile" >&2 | |
exit 1 | |
fi | |
printf "Input %q MFA: " "$AWS_PROFILE" | |
read -r TOKEN_CODE | |
SERIAL_NUMBER=$(aws iam --profile="$AWS_PROFILE" list-mfa-devices | jq -r '.MFADevices[0].SerialNumber // empty') | |
if [ -z "$SERIAL_NUMBER" ]; then | |
echo 'Failed to get Serial Number' >&2 | |
exit 1 | |
fi | |
SESSION_JSON=$(aws --profile="$AWS_PROFILE" sts get-session-token --serial-number="$SERIAL_NUMBER" --token-code="$TOKEN_CODE" --output=json) | |
# shellcheck disable=SC2181 | |
if [ $? -ne 0 ]; then | |
echo 'Failed to get session token' >&2 | |
exit 1 | |
fi | |
MFA_ACCESS_KEY=$(echo "$SESSION_JSON" | jq -r '.Credentials.AccessKeyId') | |
MFA_SECRET_ACCESS_KEY=$(echo "$SESSION_JSON" | jq -r '.Credentials.SecretAccessKey') | |
MFA_SESSION_TOKEN=$(echo "$SESSION_JSON" | jq -r '.Credentials.SessionToken') | |
MFA_EXPIRATION=$(echo "$SESSION_JSON" | jq -r '.Credentials.Expiration') | |
## MFA プロファイルは、AWS_PROFILE の suffix を付けたものにする | |
MFA_PROFILE_NAME="${AWS_PROFILE}${MFA_PROFILE_SUFFIX}" | |
aws --profile="$MFA_PROFILE_NAME" configure set aws_access_key_id "$MFA_ACCESS_KEY" | |
aws --profile="$MFA_PROFILE_NAME" configure set aws_secret_access_key "$MFA_SECRET_ACCESS_KEY" | |
aws --profile="$MFA_PROFILE_NAME" configure set aws_session_token "$MFA_SESSION_TOKEN" | |
# JSON フォーマットで結果を出力 | |
jq -n '{ profile: $profile, expiration: $expiration }' \ | |
--arg profile "$MFA_PROFILE_NAME" \ | |
--arg expiration "$MFA_EXPIRATION" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment