How to create a systemd "start all" template unit file from an upstart script with multiple services?

IRGeekSauce asked:

I’m in the process of migrating all custom upstart scripts to systemd. I’ve come across a script that utilizes multiple services. I cannot figure out the proper syntax to handle this, or if I need to just create separate .service unit files for each. Is this possible for templating? The SystemD Unit Documentation doesn’t give me much information, except for how to create a template file (appending @ to the name), and how to use %i to signify an instance.

The original upstart dealer-start-all.conf

console log
start on dealer-start
script
    declare -a dealers=("TimeZone" "Timeout" "Inquiry" "Refuse")

    for type in "${dealers[@]}"
    do
        if initctl list | grep "^dealer ($type)"
        then
            stop dealer type=$type
        fi
        start dealer type=$type
        echo "dealer$type started"
    done
end script

The other part of it, dealer.conf, should be pretty cut and dry by using %i in the ExecStart portion, like:

ExecStart=/path/to/dealer%i.php

console log

instance $type

stop on dealer-stop

script
        sudo -u root php -f /path/to/dealer$type.php
end script

post-stop script

if [ -z "$UPSTART_STOP_EVENTS" ]
    then
        echo "dealer$type stopped at `date +"%F %T.%N"` Run 'initctl emit dealer-stop' then 'initctl emit dealer-start' on `hostname` to get it running again." | mail -s "dealer$type Stopped" [email protected]
    else
        echo "dealer$type was manually stopped at `date +"%F %T"`."
fi
end script

I just don’t understand how to translate the array in the first one into a systemd version? Should I break these up into individual unit files? If so, then that’s not a problem and can be easily done. I’m just unsure of syntax (if it exists) to do what the first one is doing.

My answer:


The systemd unit template is a template. You aren’t going to put the array in it. Rather you’re going to instantiate it for each instance you want, e.g.:

systemctl enable [email protected]
systemctl enable [email protected]
...

Where %i appears in the template will be replaced with what you specified.

You also can’t use %i in the binary name in ExecStart=. It must be a path that exists, and %i used in its arguments. For example:

ExecStart=/usr/bin/php -f /path/to/dealer%i.php

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.