How to stop all units belonging to the same target?

Use the PartOf= directive.

Configures dependencies similar to Requires=, but limited to stopping and restarting of units. When systemd stops or restarts the units listed here, the action is propagated to this unit. Note that this is a one-way dependency — changes to this unit do not affect the listed units.

PartOf=mycustom.target


Edit: the PartOf= directive, which did not exist at the time of writing this answer, is a better solution. See another answer for details.

There are two ways: an implicit and an explicit.

First way — StopWhenUnneeded=

The first way is to use the StopWhenUnneeded= directive. If a unit has StopWhenUnneeded=yes, it will be automatically stopped when there becomes no active unit which Wants=/Requires= the unit in question. Hence:

  • this will only work if these units are WantedBy= only by mycustom.target;
  • you will be unable to start any of these units manually (i. e. systemctl start myunit.service will start it and immediately stop it afterwards).

Second way — a shell pipeline

The second way is to construct a simple shell pipeline, using systemctl show -p to extract the dependency list of mycustom.target.

More specifically, systemctl show UNIT will show all properties of a unit in a KEY=VALUE form, and systemctl show -p PROPERTIES UNIT will do the same, limiting the set of shown properties. So:

systemctl stop -- $(systemctl show -p Wants mycustom.target | cut -d= -f2)

Tags:

Systemd