Dockerfile set ENV based on npm package version [duplicate] - node.js

Is it possible to set a docker ENV variable to the result of a command?
Like:
ENV MY_VAR whoami
i want MY_VAR to get the value "root" or whatever whoami returns

As an addition to DarkSideF answer.
You should be aware that each line/command in Dockerfile is ran in another container.
You can do something like this:
RUN export bleah=$(hostname -f);echo $bleah;
This is run in a single container.

At this time, a command result can be used with RUN export, but cannot be assigned to an ENV variable.
Known issue: https://github.com/docker/docker/issues/29110

I had same issue and found way to set environment variable as result of function by using RUN command in dockerfile.
For example i need to set SECRET_KEY_BASE for Rails app just once without changing as would when i run:
docker run -e SECRET_KEY_BASE="$(openssl rand -hex 64)"
Instead it i write to Dockerfile string like:
RUN bash -l -c 'echo export SECRET_KEY_BASE="$(openssl rand -hex 64)" >> /etc/bash.bashrc'
and my env variable available from root, even after bash login.
or may be
RUN /bin/bash -l -c 'echo export SECRET_KEY_BASE="$(openssl rand -hex 64)" > /etc/profile.d/docker_init.sh'
then it variable available in CMD and ENTRYPOINT commands
Docker cache it as layer and change only if you change some strings before it.
You also can try different ways to set environment variable.

This answer is a response to #DarkSideF,
The method he is proposing is the following, in Dockerfile :
RUN bash -l -c 'echo export SECRET_KEY_BASE="$(openssl rand -hex 64)" >> /etc/bash.bashrc'
( adding an export in the /etc/bash.bashrc)
It is good but the environment variable will only be available for the process /bin/bash, and if you try to run your docker application for example a Node.js application, /etc/bash.bashrc will completely be ignored and your application won't have a single clue what SECRET_KEY_BASE is when trying to access process.env.SECRET_KEY_BASE.
That is the reason why ENV keyword is what everyone is trying to use with a dynamic command because every time you run your container or use an exec command, Docker will check ENV and pipe every value in the process currently run (similar to -e).
One solution is to use a wrapper (credit to #duglin in this github issue).
Have a wrapper file (e.g. envwrapper) in your project root containing :
#!/bin/bash
export SECRET_KEY_BASE="$(openssl rand -hex 64)"
export ANOTHER_ENV "hello world"
$*
and then in your Dockerfile :
...
COPY . .
RUN mv envwrapper /bin/.
RUN chmod 755 /bin/envwrapper
CMD envwrapper myapp

If you run commands using sh as it seems to be the default in docker.
You can do something like this:
RUN echo "export VAR=`command`" >> /envfile
RUN . /envfile; echo $VAR
This way, you build a env file by redirecting output to the env file of your choice. It's more explicit than having to define profiles and so on.
Then as the file will be available to other layers, it will be possible to source it and use the variables being exported. The way you create the env file isn't important.
Then when you're done you could remove the file to make it unavailable to the running container.
The . is how the env file is loaded.

As an addition to #DarkSideF's answer, if you want to reuse the result of a previous command in your Dockerfile during in the build process, you can use the following workaround:
run a command, store the result in a file
use command substitution to get the previous result from that file into another command
For example :
RUN echo "bla" > ./result
RUN echo $(cat ./result)
For something cleaner, you can use also the following gist which provides a small CLI called envstore.py :
RUN envstore.py set MY_VAR bla
RUN echo $(envstore.py get MY_VAR)
Or you can use python-dotenv library which has a similar CLI.

Not sure if this is what you were looking for, but in order to inject ENV vars or ARGS into your .Dockerfile build this pattern works.
in your my_build.sh:
echo getting version of osbase image to build from
OSBASE=$(grep "osbase_version" .version | sed 's/^.*: //')
echo building docker
docker build -f \
--build-arg ARTIFACT_TAG=$OSBASE \
PATH_TO_MY.Dockerfile \
-t my_artifact_home_url/bucketname:$TAG .
for getting an ARG in your .Dockerfile the snippet might look like this:
FROM scratch
ARG ARTIFACT_TAG
FROM my_artifact_home_url/bucketname:${ARTIFACT_TAG}
alternatively for getting an ENV in your .Dockerfile the snippet might look like this:
FROM someimage:latest
ARG ARTIFACT_TAG
ENV ARTIFACT_TAG=${ARTIFACT_TAG}
the idea is you run the shell script and that calls the .Dockerfile with the args passed in as options on the build.

Related

bash - Unable to set environment variable using script

I have a scrip that gets called in a Dockerfile entrypoint:
ENTRYPOINT ["/bin/sh", "-c", "/var/run/Scripts/entrypoint.sh"]
I need to set an environment variable based on a value in a file. I am using the following command to retrieve the value: RSYSLOG_LISTEN_PORT=$(sed -nE 's/.*port="([^"]+)".*/\1/p' /etc/rsyslog.d/0_base.conf)
Locally, this command works and even running the command from the same directory that the entrypoint script is located in will result in the env var being set.
However, adding this command after export (export SYSLOG_LISTEN_PORT=$(sed -nE 's/.*port="([^"]+)".*/\1/p' /etc/rsyslog.d/0_base.conf)) in the entrypoint script does not result in the env var being set.
Additionally, trying to use another script and sourcing the script within the entrypoint script also does not work:
#!/bin/bash
. ./rsyslog_listen_port.sh
I am unable to use source as I get a source: not found error - I have tried a few different ways to use source but it doesn't seem compatible.
Can anyone help me as I have spent too much time on trying to get this to work at this point for what seems like a relatively simple task.
A container only runs one process, and then it exits. A pattern I find useful here is to make the entrypoint script be a wrapper that does whatever first-time setup is useful, then exec the main container process:
#!/bin/sh
# set the environment variable
export SYSLOG_LISTEN_PORT=$(sed -nE 's/.*port="([^"]+)".*/\1/p' /etc/rsyslog.d/0_base.conf)
# then run the main container command
exec "$#"
In your Dockerfile, set the ENTRYPOINT to this script (it must use JSON-array syntax, and it must not have an explicit sh -c wrapper) and CMD to whatever you would have set it to without this wrapper.
ENTRYPOINT ["/var/run/Scripts/entrypoint.sh"]
CMD ["rsyslog"]
Note that this environment variable will be set for the main container process, but not for docker inspect or a docker exec debugging shell. Since the wrapper sets up the environment variable and then runs the main container process, you can replace the command part (only) when you run the container to see this.
docker run --rm your-image env \
| grep SYSLOG_LISTEN_PORT
(source is a bash-specific extension. POSIX shell . does pretty much the same thing, and I'd always use . in preference to source.)

Access $HOME in Dockerfile ENV instruction

I'm trying to set an environment variable with ENV instruction dynamically using $HOME variable (i think its a system environment variable).
But ENV is not able to access $HOME. Its blank. Although i'm able to echo $HOME.
FROM somebaseimage
....
....
USER 5051
RUN echo $HOME
# prints /home/myuser
ENV MY_JSON_FILEPATH="${HOME}/my_file.json"
RUN echo $MY_JSON_FILEPATH
# prints /my_file.json
I have tried
"${HOME}/my_file.json", "$HOME/my_file.json"; both don't work.
What would be the best way to set such environment variable?
You should add the line ARG HOME after the FROM ... line and pass build option --build-arg or add build:args parameter in your docker-compose file.

Makefile running export env having issue

I've created a Makefile to export a kubeconfig from fixed path like:
myproj
- .kube //folder
config //file which contain the config
- Makefile. //same level as .kube folder
Now when I'm running from the terminal the following it works, I mean if I run kubectl get ns I got results which means that it configure successfully!
export KUBECONFIG=/Users/i33333/projects/app-test/v-app/.kube/config
I've created a makefile target like following
kube-cfg:
export KUBECONFIG=$(PWD)/.kube/config
When execute the target I see in the terminal
export KUBECONFIG=/Users/i33333/projects/app-test/v-app/.kube/config
which exactly the same as doing that manually but when when I run kubectl get ns
I got error:
error: no configuration has been provided, try setting KUBERNETES_MASTER environment variable
I dont understand why it dosent work when I run it from makefile and works when I run it from the terminal manually ? any idea
I try to change and use also the $(CURRDIR) which doesnt help
update
I've tried like suggested which doesnt works
KUBECONFIG=$(PWD)/.kube/config
kube-cfg:
export $(KUBECONFIG)
update2
If I do it like this
KUBECONFIG := $(PWD)/kube/config.yaml
tgt1:
#export KUBECONFIG=$(KUBECONFIG) && kubectl get ns
I was able to see the ns when running the makefile tgt1: but
if now I want to run it from the terminal kubectl get ns I get the same error `error: no configuration has been provided, try setting KUBERNETES_MASTER environment variable, I want to configure it from the makefile
The problem is that makefile recipe creates new environment, which is destroyed after finishing recipe.
If you want to use kubernetes tools after calling make, more appropriate tool in your scenario is using source command. It applies in your current environment all changes made in script passed as parameter:
$ source setupenv.sh
$ kubectl get ns # should be no problem
$ make someting # even using kubectl inside make shouldn't be a problem
However if you want to use kubectl in make scripts, then create something like:
recipe :
source setupenv.sh && kubectl get ns
# or
recipe2 :
export KUBECONFIG=$(PWD)/.kube/config && kubectl get ns
UPDATE:
I thought config file is a script. So you should prepare shell script setting up environment, for example setupenv.sh:
#!/bin/bash
export KUBECONFIG=$(PWD)/.kube/config
When you run make the recipe is executed in a shell that is forked from make process. Also-recipes spanning multiple, each line (unless chained over newline escape) also gets its own shell child process. This effectively means, whatever happens (shell variable assignments or exports) in any of these shells, has no impact on the make itself or other recipe lines.
You could define for instance a make variable (as you have done in the update) and then you can set that in an environment for any command (somecmd) you are trying to run, e.g.:
some_target:
export KUBECONFIG=$(KUBECONFIG); somecmd
or:
some_target:
KUBECONFIG=$(KUBECONFIG) somecmd
In that case KUBECONFIG refers to a make variable, like the one you've defined above:
KUBECONFIG := $(PWD)/.kube/config
I.e. like this:
KUBECONFIG := $(PWD)/.kube/config
all: tgt1 tgt2
tgt1:
#export KUBECONFIG=$(KUBECONFIG); echo "KUBECONFIG is $${KUBECONFIG}"
tgt2:
#KUBECONFIG=$(KUBECONFIG) sh -c 'echo KUBECONFIG is $${KUBECONFIG}'
Yielding:
$ make
KUBECONFIG is /tmp/.kube/config
KUBECONFIG is /tmp/.kube/config
So, if you're after something that does persists also after the make is done, you need to write it out. E.g. a wrapper, such such as:
KUBECONFIG := $(PWD)/kube/config.yaml
.PHONY: call
# run callme.sh being the first prerequisite.
call: callme.sh
./$<
# creates and sets exec bit on rule target here being callme.sh
callme.sh:
#echo -e '#!/bin/bash\nKUBECONFIG=$(KUBECONFIG) kubectl get ns' > $#
chmod +x $#
This make you can run make and target call calls the wrapper... and you're also left with a wrapper callme.sh you can run after make is done.

How to pass environment variables from a file to a node command

I have a command I've installed via npm (db-migrate). I want to run it from the command line as part of automating database migration. The config file for the script can reference environment variables. I'm already setting database credentials as environment variables in another file. So rather than set them twice, I told the migration config to use the environment variables. The problem is, how do I get the environment variables from the file before running the migration script? Also, how can I run the migration script directly from the npm bin?
I found a nice general solution to this problem, so I'm posting the question and the answer for at least the benefit of my future self.
This can be done using a few tools:
Read the environment variables from the file and set them before running the script. To review, it's simple to set an environment variable before running a command:
PORT=3000 node index.js
But we want to read the variables from a file. This can be done using export and xargs:
export $(cat app.env | xargs)
We want to run the script directly from npm's bin. The path to the bin folder can be obtained using npm bin. So we just need to add that to the path before running the command:
PATH=$(npm bin):$PATH
Now put them together:
export $(cat app.env | xargs) && PATH=$(npm bin):$PATH db-migrate up
This reads the environment variables, sets them, adds the npm bin to the path, and then runs the migration script.
By the way, the content of app.env would look something like this:
PORT=3000
DB_NAME=dev
DB_USER=dev_user
DB_PASS=dev_pass
UPDATE:
There are a few caveats with this method. The first is that it will pollute your current shell with the environment variables. In other words, after you run the export...xargs bit, you can run something like echo $DB_PASS and your password will show up. To prevent this, wrap the command in parens:
(export $(cat app.env | xargs) && PATH=$(npm bin):$PATH db-migrate up)
The parens cause the command to be executed in a subshell environment. The environment variables will not bubble up to your current shell.
The second caveat is that this will only work if your environment variables don't have spaces in them. If you want spaces, I found an OK solution based on this gist comment. Create a file named something like load-env.sh:
# loads/exports env variables from a file
# taken from: https://gist.github.com/judy2k/7656bfe3b322d669ef75364a46327836#gistcomment-3239799
function loadEnv() {
local envFile=$1
local isComment='^[[:space:]]*#'
local isBlank='^[[:space:]]*$'
while IFS= read -r line; do
[[ $line =~ $isComment ]] && continue
[[ $line =~ $isBlank ]] && continue
key=$(echo "$line" | cut -d '=' -f 1)
value=$(echo "$line" | cut -d '=' -f 2-)
eval "export ${key}=\"$(echo \${value})\""
done < "$envFile"
}
Then run your command like this:
(source scripts/load-env.sh && loadEnv app.env && PATH=$(npm bin):$PATH db-migrate up)

How to specify LD_LIBRARY_PATH via add_custom_command?

I am trying to add ld_library_path via cmake.
What I have done so far is
add_custom_command(TARGET ${target}
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:${target}> ${PROJECT_BINARY_DIR}/bin
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
COMMAND $<TARGET_FILE:${target}>
################ ENV Set here ####################
-E env "LD_LIBRARY_PATH=$ENV{LD_LIBRARY_PATH}:${PROJECT_SOURCE_DIR}/boost_linux/lib"
COMMENT "Running Tests Now .. " VERBATIM
)
But I am still getting linking error during runtime. Does any one know how to properly link lib path.
In bash it would be like
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/path/to/lib
It's not clear what exactly you're trying to achieve and how it is related to a linking error. But the way you run commands with custom environment variables is the following:
add_custom_command(
...
COMMAND ${CMAKE_COMMAND} -E env "LD_LIBRARY_PATH=..."
actual command line that you need to execute
)
So, -E env works such that it executes whatever is passed after env variable specification.
Note, however, that you cannot use multiple COMMAND arguments and set env in the first one while using it in the following COMMANDs - it won't work. Or, at least, it is generator-dependent. With Make backend this is translated into multiple calls to shell - so it sets the env but the rest of commands are executed separately and don't see it. Ninja generator translates multiple COMMANDs into something like cmd1 && cmd2 && ... so it works there, AFAIK.

Resources