Last active
March 8, 2024 15:02
-
-
Save noizo/2c0b6a5e479914c20f3cde1cb668d530 to your computer and use it in GitHub Desktop.
Refresh your aws secret key
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
function renew_aws_key() { | |
# If no arguments are passed, print usage and exit with error | |
[ -z "$1" ] && echo "Usage: renew_aws_key <user_name> <profile>" && return 1 | |
# Assign variables for user name and profile name | |
local user_name="$1" | |
local profile_name="${2:-default}" | |
# List the access keys for the specified user | |
local keys=$(aws iam list-access-keys --user-name "$user_name" --output json) | |
# Extract active keys from the output | |
local active_keys=$(echo $keys | jq -r '.AccessKeyMetadata[] | select(.Status == "Active") | .AccessKeyId' || echo "No active access keys found for user $user_name" && return 1) | |
# Get the first active key | |
local old_key=$(echo $active_keys | head -1) | |
# Ask for user confirmation before proceeding with deletion | |
read -p "About to delete the old access key: $old_key. Are you sure you want to delete this key? [y/N] " response | |
# If user input does not match 'yes' or 'y', print cancel message and exit with error | |
[[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]] || echo "Operation cancelled." && return 1 | |
# Create a new access key for the specified user | |
local new_access_key=$(aws iam create-access-key --user-name "$user_name") | |
echo "Successfully created new access key." | |
# Extract key id and secret from the output | |
local new_key=$(echo $new_access_key | jq -r '.AccessKey.AccessKeyId') | |
local new_secret=$(echo $new_access_key | jq -r '.AccessKey.SecretAccessKey') | |
# Delete the old access key | |
aws iam delete-access-key --user-name "$user_name" --access-key-id $old_key | |
# Set the new access key id and secret in the AWS configuration | |
aws configure set aws_access_key_id $new_key --profile $profile_name | |
aws configure set aws_secret_access_key $new_secret --profile $profile_name | |
# Print confirmation message | |
echo "New access key $new_key has been created and updated in the AWS configuration." | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment