Skip to content

Instantly share code, notes, and snippets.

@rhighs
Created June 25, 2025 08:11
Show Gist options
  • Select an option

  • Save rhighs/0582974ce905d5bdf72226e8bbfb732d to your computer and use it in GitHub Desktop.

Select an option

Save rhighs/0582974ce905d5bdf72226e8bbfb732d to your computer and use it in GitHub Desktop.
Support bash function useful for updating/exporting aws sso login stuff as key_id/secret credentials values
#!/bin/bash
refresh-aws-keys () {
if [[ "$1" == "-h" || "$1" == "--help" || -z $1 ]]; then
echo "usage: refresh-aws-keys <aws_profile>"
echo ""
echo "refreshes AWS SSO credentials for the given profile if expired or missing."
echo "updates ~/.aws/credentials with new keys."
echo ""
return 0
fi
local profile="$1";
local creds_file="$HOME/.aws/credentials";
local expiry;
expiry=$(aws configure get expiration --profile "$profile" 2>/dev/null);
local now;
now=$(date -u +"%Y-%m-%dT%H:%M:%SZ");
if [[ -z "$expiry" || "$expiry" < "$now" ]]; then
echo "[$profile]: credentials expired or missing, refreshing...";
aws sso login --profile "$profile" || return 1;
eval "$(aws configure export-credentials --profile $profile --format env)"
access_key=$AWS_ACCESS_KEY_ID;
secret_key=$AWS_SECRET_ACCESS_KEY;
session_token=$AWS_SESSION_TOKEN;
if grep -Fxq "[$profile]" "$creds_file"; then
awk -v p="[$profile]" -v ak="$access_key" -v sk="$secret_key" -v st="$session_token" '
$0==p {
f=1
print p
print "aws_access_key_id="ak
print "aws_secret_access_key="sk
print "aws_session_token="st
next
}
/^\[.*\]$/ { f=0 }
!f
' $creds_file > /tmp/refresh-aws-keys.tmp && mv /tmp/refresh-aws-keys.tmp $creds_file;
else
{
echo ""
echo "[$profile]"
echo "aws_access_key_id=$access_key"
echo "aws_secret_access_key=$secret_key"
echo "aws_session_token=$session_token"
} >> "$creds_file"
fi
echo "[$profile]: credentials updated successfully";
aws sts get-caller-identity --profile "$profile";
else
mins_left=$(( ( $(date -d "$expiry" +%s) - $(date -u +%s) ) / 60 ));
echo "[$profile]: credentials valid for $mins_left more minutes";
aws sts get-caller-identity --profile "$profile";
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment