Closed ledjon closed 1 year ago
This solution above is nice! Here is what I came up with. Might be helpful to somebody, so I'll leave it here. I also ran into some slight issues with the bash example.
Issue 1: the env file can't have double quotes on the value. In the example:
SECRET_KEY="hip-hip-env-files"
This resulted in an env var of:
declare -x SECRET_KEY="\"hip-hip-env-files\""
So I stripped out all the double quotes.
SECRET_KEY=hip-hip-env-files
which resulted in
declare -x SECRET_KEY="hip-hip-env-files"
Issue 2: Blank and Commented out (#) lines cause issues
If any of the lines are commented out, or just blank newlines, it ran export
which dumped all my env vars to my screen. I fixed that with:
while read -r line; do
[[ $line =~ ^#.* ]] && continue
[ -z $line ] && continue
export $line;
done < .env
Thanks for tips! Would welcome a PR to docs!
Another option, which I'm using because my .env
has if[]
s and other structures that don't parse nicely.
source .env; env > temp_captured_env_vars
temp_captured_env_vars
Instead of attempting to parse the bash file, just execute it to export whatever variables it likes and load all environment variables to a temporary file, which the plugin can handle as a .env
file. This works fairly seamlessly - it will pick up changes to the bash file when you run your application, and the bash file doesn't need any particular structure or care.
WARNINGS/notes:
the first time you run, the plugin complains that it can't find your temporary file. Just run again, and it will work. There is an option for tell to ignore files it cannot find.
More importantly, the latest version includes an option to execute any file, and interpret stdout as .env
or JSON/YAML
with env vars. So you could add an extra script like:
. my-env.sh
env
which should output all the env vars including those that are set in the script. Will need to update the readme.
The bash workaround documented in the README talks about reading in the file and (re)-exporting the variables (lines in the file) 1-by-1. There is an easier/cleaner/more-correct solution that still allows comments in the .env file (i.e., treats it like bash script still). Basically you use
set -a
which will treat all variables that are set as exports. The secondset +a
disables this behavior for the rest of the script (back to default behavior).env:
set-env.sh
See SF post on similar topic: https://unix.stackexchange.com/a/79084
Just thought I'd pass this along for other users that think the solution in the README is just a little bit too hacky 😄