Created
October 29, 2023 21:44
-
-
Save pietersp/fb29e52a55684a7d3b93b2b1de830da2 to your computer and use it in GitHub Desktop.
Fills in env vars in template and runs it on remote postgres
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
#!/bin/bash | |
# commands used in this script | |
required_commands=("gum" "envsubst") | |
# Ensure the required commands are installed | |
for cmd in "${required_commands[@]}"; do | |
if ! type "$cmd" &> /dev/null; then | |
echo "Error: $cmd not found in PATH. Please install it first:" | |
exit 1 | |
fi | |
done | |
# create temp file for envsubst and clean up after script | |
temp_file=$(mktemp) | |
trap 'rm -f "$temp_file"' EXIT | |
# Check if the script was passed a file | |
if [[ $# -eq 0 ]]; then | |
echo "Please select a template file to use" | |
file=$(gum file .) | |
else | |
file=$1 | |
fi | |
# Check if the template file exists | |
if [[ ! -f $file ]]; then | |
echo "Error: File: $file does not exist" | |
exit 1 | |
fi | |
# Get all the variables from the input file that start with $ | |
vars=$(grep -oP '(?<=\$)[A-Za-z0-9_]+' "$file" | sort | uniq) | |
# for each variable use gum to prompt the user for a value and set the environmental variable | |
for var in $vars; do | |
user_value=$(gum input --placeholder "Enter value for $var: ") | |
export "$var=$user_value" | |
echo "$var set to $user_value" | |
done | |
# substitute the variables in the input file and output to a temp file | |
envsubst < "$file" > "$temp_file" | |
gum pager < "$temp_file" | |
cat $temp_file | gum format -t code | |
gum confirm "Does the contents look correct?" --default=false || exit 1 | |
# run the postgres query with the contents of the populated script | |
echo "ssh $server 'psql ' <$temp_file" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment