Thom Thom Thom
Thom Thom Thom

Reputation: 1319

Dockerfile - Defining an ENV variable with a dynamic value

I want to update the PATH environment variable with a dynamic value. This is what I've tried so far in my Dockerfile:

...
ENV PATH '$(dirname $(find /opt -name "ruby" | grep -i bin)):$PATH'
...

But export shows that the command was not interpreted:

root@97287b22c251:/# export
declare -x PATH="\$(dirname \$(find /opt -name \"ruby\" | grep -i bin)):\$PATH"

I don't want to hardcode the value. Is it possible to achieve it?

Thanks

Upvotes: 19

Views: 11062

Answers (3)

stoft
stoft

Reputation: 1275

Since it's a path you can symlink to it and then reference the symlink. Here's one I needed for an old Java project:

# Java is installed in /usr/lib/jvm/temurin-8-jdk-arm64
# or /usr/lib/jvm/temurin-8-jdk-amd64 depending on the platform
RUN ln -sf $(dirname $(dirname $(readlink -f $(which java)))) /usr/lib/jvm/java-home
ENV JAVA_HOME=/usr/lib/jvm/java-home

Upvotes: 0

Stephen Ng'etich
Stephen Ng'etich

Reputation: 998

we can't do that, as that would be a huge security issue. Meaning you could run and environment variable like this

 ENV PATH $(rm -rf /)

However, you can pass the information through a --build-arg (ARG) when building an image;

ARG DYNAMIC_VALUE 
ENV PATH=${DYNAMIC_VALUE:-unknown}
RUN echo $PATH

and build an image with:

> docker build --build-arg DYNAMIC_VALUE=$(dirname $(find /opt -name "ruby" | grep -i bin)):$PATH .

Or, if you want to copy information from an existing env-var on the host;

> export DYNAMIC_VALUE=foobar
> docker build --build-arg DYNAMIC_VALUE .

Upvotes: 5

Thomas
Thomas

Reputation: 732

Not sure if something like this is what you are looking for... slightly modified what you have already. My main question would be, what are you attempting to accomplish with this portion?: '$(dirname $(find /opt -name "ruby" | grep -i bin)):$PATH' Part of the problem could be usage of single and double quotes resulting in expansions.

FROM alpine:3.4
RUN PATH_TO_ADD=$(dirname $(find /opt -name "ruby" | grep -i bin)) || echo Error locating files
ENV PATH "$PATH:$PATH_TO_ADD"

Upvotes: -2

Related Questions