Skip to content

Instantly share code, notes, and snippets.

@imdurgadas
Last active May 6, 2023 06:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imdurgadas/6e2966acce6d33578c7f74a2c1b91af2 to your computer and use it in GitHub Desktop.
Save imdurgadas/6e2966acce6d33578c7f74a2c1b91af2 to your computer and use it in GitHub Desktop.
Generate .aws/credentials file from SSO temporary credentials.
#!/bin/bash
set -e
# Set the profile name
profile_name=$1
region=ap-south-1
# Run the command to export SSO credentials
sso_export=$(aws-sso-creds export --profile "$profile_name")
# Extract the access key, secret key, and session token from the export output
aws_access_key_id=$(echo "$sso_export" | grep AWS_ACCESS_KEY_ID | cut -d= -f2)
aws_secret_access_key=$(echo "$sso_export" | grep AWS_SECRET_ACCESS_KEY | cut -d= -f2)
aws_session_token=$(echo "$sso_export" | grep AWS_SESSION_TOKEN | cut -d= -f2)
# Create or update the AWS credentials file
creds_file=~/.aws/credentials
if [ -f "$creds_file" ]; then
# Create a temporary file to store updated credentials
tmp_file=$(mktemp)
# Flag to track if the profile exists in the credentials file
profile_exists=false
while read -r line; do
if echo "$line" | grep -q "^\[$profile_name\]$"; then
# Found the profile, update the credentials
profile_exists=true
echo "$line" >> "$tmp_file"
echo "aws_access_key_id=$aws_access_key_id" >> "$tmp_file"
echo "aws_secret_access_key=$aws_secret_access_key" >> "$tmp_file"
echo "aws_session_token=$aws_session_token" >> "$tmp_file"
echo "region=$region" >> "$tmp_file"
# Skip the existing credentials for the profile
while read -r sub_line; do
if [ "$sub_line" = "" ]; then
break
fi
done
else
echo "$line" >> "$tmp_file"
fi
done < "$creds_file"
# If the profile does not exist, append the credentials to the temporary file
if [ "$profile_exists" = false ]; then
echo -e "\n[$profile_name]" >> "$tmp_file"
echo "aws_access_key_id=$aws_access_key_id" >> "$tmp_file"
echo "aws_secret_access_key=$aws_secret_access_key" >> "$tmp_file"
echo "aws_session_token=$aws_session_token" >> "$tmp_file"
echo "region=$region" >> "$tmp_file"
fi
# Replace the original credentials file with the updated file
mv "$tmp_file" "$creds_file"
else
# Create a new credentials file
echo -e "[$profile_name]\naws_access_key_id=$aws_access_key_id\naws_secret_access_key=$aws_secret_access_key\naws_session_token=$aws_session_token\nregion=$region" > "$creds_file"
fi
echo "AWS credentials file updated with credentials for profile '$profile_name'"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment