Search code examples
systemd

Ensuring that a systemd unit starts *before* any networking


I have some code which I need to ensure runs until completion before any networking units start, as amongst other things that code generates dhcpcd.conf and wpa_supplicant.conf.

This ought to be straightforward but all my efforts so far have been in vain...

My current unit looks like this:

[Unit]
Description=Config generation from DB
Before=networking.service

[Service]
Type=oneshot
ExecStart=/home/mark/bin/db2config.py

[Install]
RequiredBy=network.target

I have tried several variations on this theme (including adding dhcpcd.service to the Before= list, for example) but none have had the desired effect.

My understanding of Before= is that any of the listed services which are going to be started, will not start until after this unit. But that understanding is clearly wrong!

This feels like something that would already have come up, but if so I've not found it amongst the far more common questions about making sure networking has started before some other unit does.


Solution

  • The answer is fairly simple, but it requires removing the assumption that OS-supplied units necessarily do what you think they do.

    Firstly, my (now working) unit:

    [Unit]
    Description=Config generation from DB
    Before=network-pre.service
    Wants=network-pre.service
    
    [Service]
    Type=oneshot
    ExecStart=/home/mark/bin/db2config.py
    
    [Install]
    RequiredBy=network.target
    

    But the all important change is to make dhcpcd depend on network-pre.target which out of the box on many/most distros (eg Debian, Redhat) it does not:

    sudo systemctl edit dhcpcd.service

    .. and add:

    [Unit]
    After=network-pre.target
    

    Thanks to the systemd-devel mailing list for helping me on this: