Created
February 29, 2024 19:14
-
-
Save vincent-zurczak/77fa9d1447b2e8ae37231abd2c7ff49a to your computer and use it in GitHub Desktop.
Replace values by env vars (envsubst opposite)
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 | |
# 1. Let's assume we have a 'secrets.env' file that lists variables and their values. | |
# | |
# ENV_1=VALUE_1 | |
# ENV_2=VALUE_2 | |
# ENV_3=VALUE_3 | |
# | |
# And we have a file that contains hard-coded values, e.g. | |
# my_content is VALUE_3 | |
# | |
# We want this script to transform it into... | |
# my_content is ${ENV_3} | |
# | |
# Somehow, this is almost the opposite of the envsubst command. | |
# "envsubst" substitutes placeholders by env values. | |
# Here, we replace env values by placeholders. | |
# With special characters support, etc. | |
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) | |
while IFS= read -r line | |
do | |
VAR=$(echo $line | cut -d "=" -f 1) | |
VALUE=$(echo $line | cut -d "=" -f 2) | |
echo $VALUE | |
# Escape special characters for sed | |
CLEANED_VALUE=$(sed -e 's/[&\\/]/\\&/g; s/$/\\/' -e '$s/\\$//' <<<"$VALUE") | |
# Replace values by a reference to their env variable | |
sed -i "s@$CLEANED_VALUE@\${$VAR}@g" my_file_to_update | |
done < "$SCRIPT_DIR/secrets.env" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Obviously, this would require some automated tests to verify all the cases.
I tested values with special chars like
?
and&
, but not with@
. This gist is more a sticky note I created at the end of a busy day: it may be updated later.