Systemd: Restart all instances of an Instantiated Service at once

Solution 1:

Systemd (starting from systemd-209) supports wildcards, however your shell is likely trying to expand them. Use quotes to pass wildcards to the systemctl/service command verbatim:

systemctl restart 'autossh@*'

Solution 2:

Not nice, but this works for systems with an old systemd:

systemctl list-units -t service --full| cut -d' ' -f1| grep mypattern | while read s; do systemctl restart $s; done

Of course the solution from above answer (systemctl restart 'autossh@*') is better.


Solution 3:

@weirdan Answer is correct, but is missing something for certain distributions.

For Centos 7 and similar, you can do:

systemctl (start|stop|restart|status) my-service@*

BUT, (start) will work ONLY, if you specify the flag "--all" :

systemctl (start) my-service@* --all

Otherwise, it will not find the services, since they do not exist. This is systemd intended feature.

For Ubuntu based systems, it works pretty much the same way, but the difference is, that the "--all" flag must be specified for all of the systemctl arguments, otherwise it will not do anything.

systemctl (start|stop|restart|status) 'my-service@*' --all

Solution 4:

I don't know if it's there an option for a wildcard on the terminal for systemd. The what you can do is adding one on your systemd scripts.

The %i would do the trick I think but is related on the way you scripted the instantiated services.

You may find an explanation here referred as specifiers

which shows that:

%n

full unit name

%p

For instantiated units, this refers to the string before the "@" character of the unit name. For non-instantiated units, this refers to the name of the unit with the type suffix removed.

%i

For instantiated units: this is the string between the "@" character and the suffix of the unit name.unit name

I'm not directly answering your question, but for what I guess you are trying to achieve. If you think your solution may be found following this idea, please share your systemd script, so we can eventually illustrate with examples and maybe even providing you the final script.

If you feel confident in editing your own script to reach a solution that way, here you have an example (I won't quote it as I don't know if it is relevant for the solution, and is too specific to what I'm proposing)

Tags:

Systemd