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
ϹοδεMεδιϲ
  • 2,790
  • 3
  • 33
  • 54

2 Answers2

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
...
xoryves
  • 1,447
  • 18
  • 13
  • 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. – Xabs Sep 19 '16 at 14:02
  • Juts converted my comment into a proper question: http://stackoverflow.com/questions/39576006/systemd-prepending-bin-to-environment-path – Xabs Sep 19 '16 at 14:46
  • 3
    This answer works for setting PATH (`Environment="PATH=/local/bin`), but not appending/prepending to PATH (`Environment="PATH=/local/bin:$PATH"`), right? – Jérôme Oct 13 '17 at 07:30
  • You are right @Jérôme. It seems, that appending to Environment is not desired. See https://github.com/systemd/systemd/issues/1082. – xoryves Oct 13 '17 at 13:01
  • 1
    A very important section is contained in the man pages `systemd.exec` https://www.freedesktop.org/software/systemd/man/systemd.exec.html#Environment%20variables%20in%20spawned%20processes 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=)_ – MatteoOreficeIT Mar 28 '19 at 10:03
-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.

ϹοδεMεδιϲ
  • 2,790
  • 3
  • 33
  • 54
krish7919
  • 892
  • 2
  • 13
  • 30