1

I want to migrate a SysV service that is in a script to a unit file in systemd. I have two machines, one main and one secondary. On both machines the service will be enabled at startup, but the service will always run on the main one. I want to add an ExecCondition, to verify the status of the service on the other machine, and depending on this continue with the execution of the following commands or directly do nothing.

systemctl is-active myservice -H kbc01

this command displays the active or inactive state

active (0)
inactive (3)

My idea is that if the service in the other machine is active (0) that the following ExecStart commands are not executed. If the service on the other machine is down (3) let the following Execstart commands run.

the systemd documentation says the following ExecCondition= command exits with exit code 1 through 254 (inclusive), the remaining commands are skipped and the unit is not marked as failed.

How can I make it do the opposite?

Main machine (kbc01):

[Unit]
Description=Aplication 
After=local-fs.target network-online.target

[Service] 
ExecCondition=systemctl is-active myservice -H kbc01
ExecStart=/home/user/aplication/bin/myservicestart
ExecStop=/home/user/aplication/bin/myserviceshutdown 
Restart=on-failure

[Install] 
WantedBy=multi-user.target

Secondary machine (kbc02):

[Unit] 
Description=Aplication 
After=local-fs.target network-online.target

[Service]
ExecCondition=systemctl is-active myservice -H kbc02 
ExecStart=/home/user/aplication/bin/myservicestart
ExecStop=/home/user/aplication/bin/myserviceshutdown
Restart=on-failure

[Install]
WantedBy=multi-user.target

1 Answer 1

2

Instead of calling systemctl is-active directly, you could call a bash script with your logic:

[Service]
ExecCondition=/usr/local/sbin/myservice-is-needed kbc02
#!/bin/bash
# /usr/local/sbin/myservice-is-needed

systemctl is-active myservice -H "$1"
retval=$?

if [ "$retval" -ne 0 ]; then 
    exit 0;
fi

exit 1

Or make it a 1-liner:

[Service]
ExecCondition=/bin/bash -c '! systemctl is-active myservice -H kbc02'
1
  • 1
    Just ! systemctl is-active myservice -H "$1" should be sufficient
    – muru
    Commented Apr 29, 2022 at 6:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .