Skip to content

Instantly share code, notes, and snippets.

@loperd
Created March 19, 2023 10:43
Show Gist options
  • Save loperd/22112a376a5b2579002744975e37198a to your computer and use it in GitHub Desktop.
Save loperd/22112a376a5b2579002744975e37198a to your computer and use it in GitHub Desktop.
Dump env from Kubernetes secret & configmap which maps to global container ENVs.
#!/bin/bash
set -e
ENV_SOURCE_FILE='.env'
OUTPUT_FILENAME='.env.production.local'
SECRET_DIRNAME='monoplace'
POSITIONAL=()
while [[ $# -gt 0 ]]; do
key="$1"
case $key in
-s | --secret)
SECRET_DIRNAME="$2"
shift
shift
;;
-e | --env-source)
ENV_SOURCE_FILE="$2"
shift
shift
;;
-o | --output)
OUTPUT_FILENAME="$2"
shift
shift
;;
*)
POSITIONAL+=("$1")
shift
;;
esac
done
set -- "${POSITIONAL[@]}"
SECRET_CATALOG="/etc/${SECRET_DIRNAME}"
if [ ! -d "${SECRET_CATALOG}" ]; then
echo -e "Secret \"${SECRET_CATALOG}\" does not exist\n"
exit
fi
if [ ! -f "$ENV_SOURCE_FILE" ]; then
echo -e "File '$ENV_SOURCE_FILE' does not exists in this directory."
exit;
fi
OUTPUT_FILE="./$OUTPUT_FILENAME"
rm "$OUTPUT_FILE"
touch "$OUTPUT_FILE"
# shellcheck disable=SC2002
cat "$ENV_SOURCE_FILE" | while IFS="=" read -r key value; do
SECRET_FILE="$SECRET_CATALOG/$key"
if [ -f "$SECRET_FILE" ]; then
echo "$key=$(cat "$SECRET_FILE")" >> "$OUTPUT_FILE"
echo "Find $key in the secret '$SECRET_FILE'"
continue
fi
if [ -n "$(printenv "$key")" ]; then
echo "$key=$(printenv "$key")" >> "$OUTPUT_FILE"
echo "Find $key in the global env"
continue
fi
echo "Doesn't find $key anywhere, use default"
echo "$key=$value" >> "$OUTPUT_FILE"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment