The following script is useful for when you want to include variables in your React or Angular web app, but don't want 2 or more container images in your container registry.
First, you'll need some environment variables. Here are some examples:
export inject_arg_REACT_APP_VARIABLE_ONE=value1
Then you'll need to make sure your values for your .env
files are setup like
internal_react_var = inject_arg_REACT_APP_VARIABLE_ONE
When your Angular or React app then transpiles the code, all the variables are
replaced with the inject_arg_*
string. This is where the following script comes into play.
It will scan your source code looking for any inject_arg_*
string, make an array/list of
them, and then find all .js
files and replace that string with the environment variable
matching that string with the value.
#!/usr/bin/env bash
#set -x
set -e
cp --recursive /app/* /usr/share/nginx/html
# Get an array/list of the inject_arg_ variables found.
vars=( $(grep -h -o "inject_arg_[a-zA-Z_0-9-]\+" $(find /usr/share/nginx/html -type f -name "*.js") | sort -u ) )
for var in "${vars[@]}"
do
echo "Found: ${var}"
done
for js_file in $(find /usr/share/nginx/html -type f -name "*.js")
do
echo "Replacing ${var} in: ${js_file}"
for var in "${vars[@]}"
do
sed --in-place --expression="s|${var}|$(printenv ${var})|g" ${js_file}
done
done
#starting nginx
nginx -g 'daemon off;'
You'll see there's a cp
command. This is used becasue when we deploy this, our filesystems
are set to read-only, and we mount an emptyDir into the /usr/share/nginx/html directory,
then we copy the app contents to that folder and replace it.