9

I have a Docker container running systemd. I want to pass environment variables to applications under it.

When I start systemd from within Docker (/sbin/init as command line), Docker exposes variables to systemd, but does not expose to child services. If I add systemd.setenv=... to the cmdline, the variables are passed. I am looking for a cleaner solution.

How do I expose environment variables passed to /sbin/init to applications started by it?

% docker run -v /sys/fs/cgroup:/sys/fs/cgroup:ro --privileged -ti \
             -e VAR1=1 motiejus/systemd_fedora20 \
             init systemd.setenv=VAR2=2
...
Welcome to Fedora 20 (Heisenbug)!
...
[  OK  ] Reached target Multi-User System.
[root@740690365eb0 ~]# env | grep VAR
VAR2=2

I expect to see VAR1=1 while running my command.

In other words, can systemd pass variables passed to it to children it starts?

For Dockerfile, see github repository.

8

To answer the question asked (as it doesn't seem to be answered anywhere else)

"How do I expose environment variables passed to /sbin/init to applications started by it?"

requires some slightly irritating bash, and an extremely useful function of the linux /proc filesystem:

# Import our environment variables from systemd
for e in $(tr "\000" "\n" < /proc/1/environ); do
        eval "export $e"
done

This reads /proc/1/envion, which is the environment given to PID 1, but is delimited by nulls. It uses 'tr' to replace the nulls with new lines, and then iterates over those lines and evals them with a prepended 'export', so they are visible to child processes.

The not-exposing-environment-variables is yet another "feature" of systemd, and they don't consider it a bug.

  • 3
    I want to say 'I do not need this feature, I need environment variables' – Daniel Dai Nov 21 '17 at 8:21
1

According to this description, a systemd user instance does not inherit environment variables:

https://wiki.archlinux.org/index.php/Systemd/User#Environment_variables

There is a suggestion here to use oneshot systemd service that configures an EnvironmentFile for the "final" service.

https://stackoverflow.com/questions/25396167/how-do-i-get-etcd-values-into-my-systemd-service-on-coreos

  • Also consider to check PassEnvironment=. It helped me in docker systemd environment. – FelikZ Nov 20 '18 at 13:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.