Search code examples
salt-projectsystemd

Salt: Condition based on systemd being available or not


I want to install this file via salt-stack.

# /etc/logrotate.d/foo

/home/foo/log/foo.log {
    compress
    # ...
    postrotate
      systemctl restart foo.service
    endscript
}

Unfortunately there are some old machines which don't have systemd yet.

For those machines I need this postrotate script:

/etc/init.d/foo restart

How to get this done in salt?

I guess I need something like this:

postrotate
 {% if ??? %}
   /etc/init.d/foo restart
 {% else %}
   systemctl restart foo.service
 {% endif %} 
endscript

But how to implement ??? ?


Solution

  • We can discover this by taking advantage of the service module, which is a virtual module that is ultimately implemented by the specific module appropriate for the machine.

    From the command line we can discover the specific module being used with test.provider. Here is an example:

    $ sudo salt 'some.*' test.provider service
    some.debian.8.machine:
        systemd
    some.debian.7.machine:
        debian_service
    some.redhat.5.machine:
        rh_service
    

    To discover this in a template we can use:

    {{ salt["test.provider"]("service") }}
    

    So, you could use something like:

    postrotate
      {% if salt["test.provider"]("service") != "systemd" %}
       /etc/init.d/foo restart
     {% else %}
       systemctl restart foo.service
     {% endif %} 
    endscript
    

    NOTE:

    The possible return value of test.provider will vary across platform. From the source, these appear to be the currently available providers:

    $ cd salt/modules && grep -l "__virtualname__ = 'service'" *.py
    debian_service.py
    freebsdservice.py
    gentoo_service.py
    launchctl.py
    netbsdservice.py
    openbsdrcctl.py
    openbsdservice.py
    rest_service.py
    rh_service.py
    smf.py
    systemd.py
    upstart.py
    win_service.py