I’m wondering how to stop all units that are grouped together by the same target.
My setup is as follows. I have several unit config files that read:
[Unit] ... [Service] ... [Install] WantedBy=mycustom.target
When I run
# systemctl start mycustom.target
Those units that “are wanted by” mycustom.target start correctly. Now, I would also like to be able stop all units that are wanted by mycustom.target. I tried:
# systemctl stop mycustom.target
This doesn’t do anything though. Is there a way to make this work without having to stop all units that are (explicitly) wanted by the same target?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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
Method 2
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 bymycustom.target; - you will be unable to start any of these units manually (i. e.
systemctl start myunit.servicewill 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)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0