Is the systemd instance name specifier %i redundant when referring to templated dependencies?

Do we need to use the instance name specifier (%i) in templates when referring to other templated services, or can we assume the instance name is inferred?

Many examples follow this pattern (e.g. Requires=bottom@%i.service), but that %i seems unnecessary, and things appear to work fine without it.

> cd ~/.config/systemd/user

> cat
# Wants=middle@%i.service

> cat middle@.service
# Requires=bottom@%i.service
ExecStart=/usr/bin/sh -c "echo middle"

> cat bottom@.service
ExecStart=/usr/bin/sh -c "echo bottom"

> systemctl --user start

> journalctl --user -f
Nov 17 22:21:02 miles-desk systemd[3064]: Starting bottom@foo.service...
Nov 17 22:21:02 miles-desk sh[4010694]: bottom
Nov 17 22:21:02 miles-desk systemd[3064]: Starting middle@foo.service...
Nov 17 22:21:02 miles-desk systemd[3064]: Finished bottom@foo.service.
Nov 17 22:21:02 miles-desk sh[4010695]: middle
Nov 17 22:21:02 miles-desk systemd[3064]: Finished middle@foo.service.

Is it safe to omit the %i specifier in templates? If so, then I’m confused why I haven’t been able to find any examples with this shorthand. Are there any gotchas to watch out for? I didn’t find any usage notes about this in the docs.

Asked By: MilesF


Requires et al. handle templating directly:

In case when the source unit is a template, the target can also be a template, in which case the instance will be "propagated" to the target unit to form a valid unit instance.

And conversely for RequiredBy and family:

A template unit may also list a template unit, in which case a generic dependency will be added where each instance of the listing unit will have a dependency on an instance of the listed template with the same instance value.

So for this use, yes, it is safe to omit %i.

Answered By: muru
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.