Systemd – Support for Toggling Mutually Exclusive Services

systemd

I have two versions of a service that I occasionally want to switch between – my-service-a and my-service-b. I want my-service-a to always be the one which is running when the system is booted. Currently, to switch between them, I have to run multiple commands, e.g. to switch from a to b

systemctl stop my-service-a
systemctl start my-service-b

and there is no enforcement by systemd that only one is running at a time – I just have to be careful.

Is there any direct support for this situation in systemd? I could see it being either support for "toggling" between services, or instantiations of a templated service, or I could see it as support for mutually-exclusive services, so that when I start my-service-b, my-service-a is automatically stopped. Or maybe there is another way entirely.

Best Answer

You can do this by adding the Conflicts= directive to the [Unit] section of your two unit files (Conflicts= in just one unit file works, too). From the man page for systemd.unit(5):

A space-separated list of unit names. Configures negative requirement dependencies. If a unit has a Conflicts= setting on another unit, starting the former will stop the latter and vice versa. Note that this setting is independent of and orthogonal to the After= and Before= ordering dependencies.

Related Question