Skip to content

Instantly share code, notes, and snippets.

@SkySails
Last active April 19, 2022 16:24
Show Gist options
  • Save SkySails/0ab9e2a6ce11850d7466f3b20e92eeba to your computer and use it in GitHub Desktop.
Save SkySails/0ab9e2a6ce11850d7466f3b20e92eeba to your computer and use it in GitHub Desktop.
A shell-script that aids developers in converting secrets from AWS Secrets Manager into `.env`-files for local use, such as with Docker.
#!/bin/bash
BLUE='\033[0;34m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color
function print_secret() {
SECRET="$@"
SECRET_ARN=$(echo $SECRET | jq -r ".ARN")
echo -e "${CYAN}Name:${NC} $(echo $SECRET | jq -r ".Name")"
echo -e "${CYAN}ARN:${NC} $SECRET_ARN"
echo -e "${CYAN}Description:${NC} $(echo $SECRET | jq -r ".Description")"
echo -e "${CYAN}Tags:\n${NC}$(echo $SECRET | jq -r ".Tags[] | \" \(.Key): \(.Value)\"")\n"
}
# Handle arguments
while [[ $# -gt 0 ]]; do
key="$1"
case "$key" in
-n|--name)
shift
SECRET_NAME="$1"
;;
-a|--account)
shift
AWS_ACCOUNT_ID="$1"
;;
-r|--region)
shift
AWS_REGION="$1"
;;
-o|--output)
shift
FILENAME="$1"
;;
*)
echo "Unknown option '$key'"
;;
esac
shift
done
if [[ ! $SECRET_NAME ]]; then
echo -e $RED"Error: No secret name specified.$NC\n\nUsage: secret2env -n <secret_name>\n"
exit 1
fi
# Use configured AWS environment if none specified
AWS_REGION=${AWS_REGION:-$(aws configure get region)}
AWS_ACCOUNT_ID=${AWS_ACCOUNT_ID:-$(aws sts get-caller-identity --query Account --output text)}
# Fetch DB credentials from AWS Secrets Manager
echo -e $CYAN"Looking for secret '$SECRET_NAME' in AWS Secrets Manager ($AWS_REGION)...$NC\n"
SM_RESPONSE=$(aws secretsmanager list-secrets --filters Key=name,Values=$SECRET_NAME | jq -r ".SecretList[] | select(.Name==\"$SECRET_NAME\")")
if [[ -z $SM_RESPONSE ]]; then
echo -e $RED"Error: Unable to find secret named '$SECRET_NAME'.$NC"
exit 1
fi
print_secret $SM_RESPONSE
read -p "Is this the correct secret? (y/n) " -n 1 -r
echo
if ! [[ $REPLY =~ ^[Yy]$ ]]
then
exit 0
fi
SECRET_JSON=$(aws secretsmanager get-secret-value --secret-id $SECRET_ARN --query SecretString --output text)
if [[ -z $SECRET_JSON ]]; then
echo -e $RED"Error: Failed to fetch credentials from Secrets Manager."$NC
exit 1
fi
# Export secret values to file
FILENAME=${FILENAME:-".env"}
echo $SECRET_JSON | jq -r 'to_entries | map("\(.key)=\"\(.value)\"") | .[]' > $FILENAME
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment