Created
August 6, 2020 13:06
-
-
Save su-kun1899/aa6622e2d9c069daaa7fbedf3363e45e to your computer and use it in GitHub Desktop.
This file contains 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 | |
# AWS のアクセスキーをローテーションするためのスクリプト | |
# PROFILE と USERNAME の変数は適当なものに書き換えて使う | |
# | |
# 注意事項 | |
# - 古いアクセスキーは削除する | |
# - $HOME/.aws/credentials を書き換える | |
set -eu | |
cd "$(dirname "${0}")" | |
readonly CREDENTIAL_FILE=${HOME}/.aws/credentials | |
readonly PROFILE=default | |
readonly USER_NAME=your_name | |
## アクセスキーの取得 | |
readonly ACCESS_KEYS=($(aws iam list-access-keys \ | |
--profile ${PROFILE} \ | |
--user-name=${USER_NAME} \ | |
| jq -r '.AccessKeyMetadata[].AccessKeyId')) | |
if [ ${#ACCESS_KEYS[@]} -gt 1 ] ; then | |
echo "アクセスキーが複数あります。単一の場合のみ実行します" >&2 | |
exit 1 | |
fi | |
## アクセスキーの作成 | |
readonly NEW_ACCESS_KEY=($(aws iam create-access-key \ | |
--profile ${PROFILE} \ | |
--user-name=${USER_NAME} \ | |
| jq -r '.AccessKey | .AccessKeyId, .SecretAccessKey')) | |
readonly NEW_KEY_ID="aws_access_key_id = ${NEW_ACCESS_KEY[0]}" | |
readonly NEW_KEY="aws_secret_access_key = ${NEW_ACCESS_KEY[1]}" | |
## 設定ファイルの書き換え | |
line_number=1 | |
while read line | |
do | |
if [ "${line}" = "[${PROFILE}]" ]; then | |
break | |
fi | |
line_number=$(expr ${line_number} + 1) | |
done < ${CREDENTIAL_FILE} | |
readonly OLD_KEY_ID="$(head -n $(expr ${line_number} + 1) ${CREDENTIAL_FILE} | tail -n 1)" | |
readonly OLD_KEY="$(head -n $(expr ${line_number} + 2) ${CREDENTIAL_FILE} | tail -n 1)" | |
### 念の為バックアップ | |
cp ${CREDENTIAL_FILE} ${TMPDIR} | |
sed -i -e "s|${OLD_KEY_ID}|${NEW_KEY_ID}|" ${CREDENTIAL_FILE} | |
sed -i -e "s|${OLD_KEY}|${NEW_KEY}|" ${CREDENTIAL_FILE} | |
## 古いアクセスキーの削除 (反映待ちのラグがあるので少し待つ) | |
sleep 10; aws iam delete-access-key \ | |
--profile ${PROFILE} \ | |
--user-name=${USER_NAME} \ | |
--access-key-id ${ACCESS_KEYS[0]} | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment