Last active
March 13, 2019 03:45
-
-
Save koshigoe/6d04fbf4f0f5b929a3110918fa8147c3 to your computer and use it in GitHub Desktop.
AWS IAM アクセストークンを更新するスクリプトのサンプル
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
#!/bin/bash -eu | |
# Find inactivated access key. | |
# | |
# # original output | |
# { | |
# "AccessKeyMetadata": [ | |
# { | |
# "UserName": "koshigoe", | |
# "AccessKeyId": "********", | |
# "Status": "Inactive", | |
# "CreateDate": "2016-02-18T05:25:50Z" | |
# }, | |
# { | |
# "UserName": "koshigoe", | |
# "AccessKeyId": "********", | |
# "Status": "Active", | |
# "CreateDate": "2019-03-13T00:16:19Z" | |
# } | |
# ] | |
# } | |
# | |
# # filtered output | |
# [ | |
# { | |
# "UserName": "koshigoe", | |
# "AccessKeyId": "********", | |
# "Status": "Inactive", | |
# "CreateDate": "2016-02-18T05:25:50Z" | |
# } | |
# ] | |
# | |
# # or | |
# | |
# [] | |
# | |
function find_inactive_access_key_id () { | |
user_name=$1 | |
aws iam list-access-keys \ | |
--user-name $user_name \ | |
--query 'AccessKeyMetadata[?Status==`Inactive`]' \ | |
| jq -r '.[0].AccessKeyId?' | |
} | |
function delete_inactive_access_key () { | |
access_key_id=$1 | |
aws iam delete-access-key --access-key-id $access_key_id | |
} | |
# Generate new access key. | |
# | |
# { | |
# "AccessKey": { | |
# "UserName": "koshigoe", | |
# "AccessKeyId": "********", | |
# "Status": "Active", | |
# "SecretAccessKey": "********", | |
# "CreateDate": "2019-03-13T00:16:19Z" | |
# } | |
# } | |
# | |
# And, deactiavte current access key. | |
# | |
# Finally, update `~/.aws/credentials`. | |
# | |
function rotate_access_key () { | |
profile=$1 | |
user_name=$2 | |
id_and_sec=($(aws iam create-access-key \ | |
--user-name $user_name \ | |
| tee -a ./tmp/aws-credentials-${user_name}.json \ | |
| jq -r '.AccessKey.AccessKeyId, .AccessKey.SecretAccessKey')) | |
aws iam update-access-key \ | |
--user-name $user_name \ | |
--status Inactive \ | |
--access-key-id $(aws configure get ${profile}.aws_access_key_id) | |
aws configure set aws_access_key_id ${id_and_sec[0]} --profile ${profile} | |
aws configure set aws_secret_access_key ${id_and_sec[1]} --profile ${profile} | |
} | |
AWS_PROFILE=$1 | |
IAM_USER_NAME=$2 | |
inactive_access_key_id=$(find_inactive_access_key_id $IAM_USER_NAME) | |
if [ -n "$inactive_access_key_id" ]; then | |
delete_inactive_access_key $inactive_access_key_id | |
fi | |
rotate_access_key $AWS_PROFILE $IAM_USER_NAME | |
aws iam list-access-keys --user-name $IAM_USER_NAME |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment