How to configure options for a systemd unit file

systemd

The systemd blog contains two articles that advice against using /etc/sysconfig or /etc/default:

What alternatives are there to configure system specific options for a systemd unit file?

Options I've considered:

  • create a template unit instead and use a specifier

The downside is that you need to specify the option every time the service is started. This is mainly useful to run multiple copies of a single service so it is not really applicable.

  • override the Execstart of the unit file locally with a unitd.d directory

The disadvantage here is that this requires to override the entire Execstart. It cannot be used to simply specify a single option.

Best Answer

It depends a little on what option you're trying to configure. If it's a folder location (like the home directory, runtime directory, etc.), systemd provides this through variables.

Otherwise, you can use an environment file to specify the options, and then have the service unit include the variables in those files. For example, the service file would contain the following (in addition to the usual parameters):

[Service]
Environment=ENV_OPTION_1=0 ENV_OPTION_2=linux
EnvironmentFile=/etc/default/program-name
ExecStart=/usr/bin/program $ENV_OPTION_1 ${ENV_OPTION_2}

EnvironmentFile points to a simple file that contains key-value pairs, like so:

ENV_OPTION_1=8913
ENV_OPTION_2=ubuntu

Environment are default options you may want to have.

The environment values are then used in ExecStart as shown above. Note that if the value may be space-separated, you need to use the ${} syntax.

Related Question