Accessing Environment Variables via Script

I have the simple need to show a google map in my app and I would like to manage the api keys using environment variables (even though the key will be bound to my site address I don’t want it to show up in my repo).

I’ve looked at the various bundlers and could use one of them but it seems like a pretty code heavy approach since I only need it for this one purpose.

My thought is that I can write my own python script to read the env variables (stored via the Netfli gui, not the toml file) and update as appropriate in my code at build time.

My question is in three parts:

  1. Any obvious security gotchas? the script is run at build time and not publicly available (except maybe in my repo but is that an issue? It doesn’t get called in prod just at build and the keys are only stored in the env variables)
  2. Within Netlify’s gui can I put a build command like , will it get run? do I need to specify python in the command or will it automatically run py files with python?
  3. Within my project tree structure where should i put the script so that it gets picked up and run? root for the project? or can i specify a path in the build command line?

Per my previous comment I am not interested in using webpack or grunt, etc. as its way more than what I need right now and can code this faster than it would take for me to explore either of those tools.

I am a newb so sorry if this is obvious to everyone else, trying to come up to speed and not break things.

Thx, Fil

The solution to this ended up being even simpler than I thought. I added a sed command that runs at build time and updates the file with the appropriate path.

The format I used is:
sed -i "s|<value_to_chage>|$<ENV_VARIABLE>|" file_name

There are many other patterns and options available with sed and you can wrap this in script with other commands as needed.

The only other change you need to make is to add the ENV_VARIABLE to Netlify through their gui interface.

Note this works for deploys initiated via changes to your repository.

1 Like

thanks for coming back and updating your question yourself - this is really helpful for other users in the future :+1: