Linux – Variables in “systemd” file

linuxsystemd

I have this systemd file:

  [Unit]
  Description=something website
  After=syslog.target
  Requires=postgresql.service

  [Service]
  ExecStart=/home/my_user/my_webapp/bin/ foreground
  ExecStop=/home/my_user/my_webapp/bin/ stop
  Restart=on-abort
  WorkingDirectory=/home/my_user/my_webapp/bin
  SyslogIdentifier=my_webapp_web_app
  User=my_user

  [Install]
  WantedBy=multi-user.target

As you can see, "my_webapp" and "my_user" are repeated many times. Is there any way to store them into variables and use the variables instead?

Best Answer

Probably the closest thing that would match your needs is using the EnvironmentFile option.

# file: /home/my_user/my_webapp/environment
# included in systemd unit my_webapp
# EnvironmentFile=-/home/my_user/my_webapp/environment
BASEDIR=/home/my_user/my_webapp

And your new unit

[Unit]
Description=something website
After=syslog.target
Requires=postgresql.service

[Service]
ExecStart=$BASEDIR/bin/ foreground
ExecStop=$BASEDIR/bin/ stop
Restart=on-abort
WorkingDirectory=$BASEDIR/bin
SyslogIdentifier=my_webapp_web_app
User=my_user

[Install]
WantedBy=multi-user.target

You would probably want your variables set differently. I'll leave that up to you to adjust.