systemd: "Environment" directive to set PATH
Asked Answered
R

2

39

What is the right way to set PATH variable in a systemd unit file? After seeing a few examples, I tried to use the format below, but the variable doesn't seem to expand.

Environment="PATH=/local/bin:$PATH"

I am trying this on CoreOS with the below version of systemd.

systemd 225
-PAM +AUDIT +SELINUX +IMA -APPARMOR +SMACK -SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT -GNUTLS -ACL +XZ -LZ4 +SECCOMP +BLKID -ELFUTILS +KMOD -IDN
Ratepayer answered 16/2, 2016 at 17:26 Comment(0)
P
50

You can't use EnvVars in Environment directives. The whole Environment= will be ignored. If you use EnvironmentFile=, then the specified file will be loaded without substitution. So PATH=/local/bin:$PATH would be exactly that, and this is probably not what you want.

Under CentOS7 the following works.

# /etc/systemd/system/nagios.service.d/env.conf
[Service]
Environment="PATH=/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin"

> sudo systemctl daemon-reload
> sudo systemctl restart nagios
> sudo cat /proc/28647/environ
...
PATH=/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
...
Protactinium answered 20/5, 2016 at 8:33 Comment(5)
This works for me, with the only exception that my PATH is prepended with /bin, and that defeats the purpose of setting my custom PATH. That is, if I add Environment="PATH=foo:bar" I end up getting PATH=/bin:foo:bar for my service.Carmoncarmona
Juts converted my comment into a proper question: #39576506Carmoncarmona
This answer works for setting PATH (Environment="PATH=/local/bin), but not appending/prepending to PATH (Environment="PATH=/local/bin:$PATH"), right?Finnic
You are right @Jérôme. It seems, that appending to Environment is not desired. See github.com/systemd/systemd/issues/1082.Protactinium
A very important section is contained in the man pages systemd.exec freedesktop.org/software/systemd/man/… that explains what is the initial environments set systemd passes to spawned services Citation: Processes started by the service manager are executed with an environment variable block assembled from multiple sources. Processes started by the system service manager generally do not inherit environment variables set for the service manager itself (but this may be altered via PassEnvironment=)Bugs
B
-1

You can use the EnvironmentFile= directive in the units section to set environment variables.

Just put the variables as key=value pairs and it will work.

The runtime just 'source's whatever file you specify.

You can create the file using the write_files directive.

Butterfly answered 18/2, 2016 at 3:2 Comment(2)
write_files directive?Arsenal
Ah well, that is a specific directive in the CoreOS launch configuration file. :)Butterfly

© 2022 - 2024 — McMap. All rights reserved.