0

I have to say that in Windows environment /Powershell I would have done it immediately, but since I have to execute this shell script inside a docker Linux image, I need your help.

I have a node.js env file where I store my environment variables, so the nodejs app can use them later.I've set some placeholders and I need to replace them substituting from the event args parameter I got from docker run command.

The content of the .env file is

NodePort={NodePort}
DBServer={DBServer}
DBDatabaseName={DBDatabaseName}
DBUser={DBUser}
DBPassword={DBPassword}
DBEncrypt= {DBEncrypt}
RFIDNodeUrlRoot={RFIDNodeUrlRoot}
RFIDStartMethod={RFIDStartMethod}
RFIDStopMethod={RFIDStopMethod}
RFIDGetTagsMethod={RFIDGetTagsMethod}

I don't know which is the best approach to open the file, replace the values from env variables, and then save it.

Anyone can please help me? Thanks

advapi
  • 3,661
  • 4
  • 38
  • 73
  • How exactly are the values getting into the container? If you're passing them via `docker run -e` options, they're already set in the process environment and your Node code should see them in `process.env`; you don't specifically need a `.env` file. – David Maze Apr 23 '20 at 18:46
  • youre right but this app can run on premise or on container and in the original (premise) it loads from .env so I need to abstract thats from container – advapi Apr 23 '20 at 18:50

1 Answers1

0

You can use envsubst which ist part of gettext-base package

see:

.env.temp

NodePort=${NodePort}   # notice the `$` before `{}`
DBServer=${DBServer}
..

Assuming you are setting environment variables with

docker run -e "NodePort=8080" -e "DBServer=foo"

Inside that container you will have to use some entrypoint.sh script to run:

envsubst \$NodePort,$\DBServer,.. < .env.temp > .env

then start your app passing .env to your nodejs app.

As an alternative you can also use sed to edit .env, which might be hard to understand.

subst_env() {
  eval val="\$$1"                  # expands environment variable to val
  sed -i "s%\$$1%${val}%g" $2      # using % as sed-delimiter to avoid escaping slashes in urls
}

subst_env 'ENV_DOCKER_DOMAIN' .env
invad0r
  • 908
  • 1
  • 7
  • 20