定期更新AWS访问密钥的最佳方法



我意识到我从未更新过muy AWS访问密钥,它们是应该定期更新的凭据,以避免攻击。

所以。。。如果它们只是在我的笔记本电脑上使用,那么在没有任何影响的情况下自动更新它们的最佳方式是什么?

最后我创建了这个bash脚本:

#!/bin/bash
set -e # exit on non-zero command
set -u # force vars to be declared
set -o pipefail # avoids errors in pipelines to be masked
echo "retrieving current account id..."
current_access_key_list=$(aws iam list-access-keys | jq -r '.AccessKeyMetadata')
number_of_current_access_keys=$(echo $current_access_key_list| jq length)
current_access_key=$(echo $current_access_key_list | jq -r '.[]|.AccessKeyId')
if [[ ! "$number_of_current_access_keys" == "1" ]]; then
echo "ERROR: There already are more than 1 access key"
exit 1
fi
echo "Current access key is ${current_access_key}"

echo "creating a new access key..."
new_access_key=$(aws iam create-access-key)
access_key=$(echo $new_access_key| jq -r '.AccessKey.AccessKeyId')
access_key_secret=$(echo $new_access_key| jq -r '.AccessKey.SecretAccessKey')
echo "New access key is: ${access_key}"
echo "performing credentials backup..."
cp ~/.aws/credentials ~/.aws/credentials.bak
echo "changing local credentials..."
aws configure set aws_access_key_id "${access_key}"
aws configure set aws_secret_access_key "${access_key_secret}"
echo "wait 10 seconds to ensure new access_key is set..."
sleep 10
echo "check new credentials work fine"
aws iam get-user | jq -r '.User'
echo "removing old access key $current_access_key"
aws iam delete-access-key --access-key-id $current_access_key
echo "Congrats. You are using the new credentials."
echo "Feel free to remove the backup file:"
echo "  rm ~/.aws/credentials.bak"

我将该脚本放入~/.local/bin以确保它在路径中,然后在.bashrc和/或.zshrc文件的末尾添加了以下行:

# rotate AWS keys if they are too old
if [[ -n "$(find ~/.aws -mtime +30 -name credentials)" ]]; then
AWS_PROFILE=profile-1 rotate_aws_access_key
AWS_PROFILE=profile-2 rotate_aws_access_key
fi

因此,每当我打开一个终端时(这是非常频繁的(,它都会检查凭据文件是否在一个多月内没有被修改,并尝试自动续订我的凭据。

可能发生的最糟糕的事情是,它可能会创建新的访问密钥,而不更新我的脚本,这应该迫使我手动删除它。

相关内容

  • 没有找到相关文章

最新更新