Skip to content

Commit

Permalink
Convert env files into js objects
Browse files Browse the repository at this point in the history
  • Loading branch information
amenasse committed May 18, 2023
1 parent 869d511 commit 79c8a08
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 13 deletions.
3 changes: 2 additions & 1 deletion frontend.Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,13 @@ RUN git clone https://github.com/h5bp/server-configs-nginx.git && \

# Build final production image
FROM nginx:1.24.0-alpine3.17
RUN apk add bash
WORKDIR /home/ubuntu/tupaia

COPY packages/devops/configs/servers.conf /etc/nginx/conf.d/servers.conf
COPY --from=h5bp server-configs-nginx/h5bp /etc/nginx/h5bp
# copy .env files into package dirs prior to nginx startup
COPY scripts/docker/nginx/copy-env.sh /docker-entrypoint.d/50-copy-env.sh
COPY scripts/docker/nginx/create-env.sh /docker-entrypoint.d/50-create-env.sh
# Use /home/ubuntu as workdir to be compatible with existing nginx config
# (packages/devops/configs/servers.conf)
WORKDIR "/home/ubuntu/tupaia"
Expand Down
12 changes: 0 additions & 12 deletions scripts/docker/nginx/copy-env.sh

This file was deleted.

41 changes: 41 additions & 0 deletions scripts/docker/nginx/create-env.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#!/bin/bash

# Convert the env files generated by the downloadEnv container into js objects.
# Run by the frontend container prior to nginx startup
tupaia_env_dir=${TUPAIA_ENV_DIR:-/env/packages}
tupaia_package_dir=${TUPAIA_PACKAGE_DIR:-/home/ubuntu/tupaia/packages}

function env-js() {
# Read $1 and write to $2 as a js object `window._env__`
# Adapted from
# https://www.freecodecamp.org/news/how-to-implement-runtime-environment-variables-with-create-react-app-docker-and-nginx-7f9d42a91d70
env_src=$1
env_js=$2

echo "window.env = {" > "$env_js"
# Read each line in .env file. Each line represents key=value pairs
while read -r line || [[ -n "$line" ]]; do
# Split env variables by character `=`
if printf '%s\n' "$line" | grep -q -e '='; then
varname=$(printf '%s\n' "$line" | sed -e 's/=.*//')
varvalue=$(printf '%s\n' "$line" | sed -e 's/^[^=]*=//')
fi

# Read value of current variable if exists as Environment variable
# otherwise use value from .env file
value=${!varname:-$varvalue}
# Append configuration property to JS file
echo " $varname: \"$value\"," >> "$env_js"
done < "$env_src"

echo "}" >> "$env_js"
}


for p in "$tupaia_package_dir"/*; do
package=$(basename "$p")
if [ -f "$tupaia_env_dir/$package/.env" ]; then
echo "creating $p/.env-config.js"
env-js "$tupaia_env_dir/$package/.env" "$p/.env-config.js"
fi
done

0 comments on commit 79c8a08

Please sign in to comment.