1

At the top of my State file, I have:

{% if grains['os'] == 'Ubuntu' %}
  {% set ubuntu = True %}
  {% set arch = False %}
{% elif grains['os'] == 'Arch' %}
  {% set ubuntu = False %}
  {% set arch = True %}
{% endif %}

Later on,

{% if ubuntu %}
cron:
{% elif arch %}
cronie:
{% endif %}
  pkg.installed
  service.running:
    - enable: True

But this isn't working; my conditionals are rendering nothing (empty strings). Even if a small refactoring would get the job done, this smells to me.

Is there a more idiomatic way to alternate small details like this with Salt without so much templating boilerplate?

Chris Tonkinson
  • 465
  • 2
  • 6
  • 18

1 Answers1

1

It's not working probably because pkg.installed must be a list, even without parameters:

pkg.installed: []

This should work:

{% if ubuntu %}
cron:
{% elif arch %}
cronie:
{% endif %}
  pkg.installed: []
  service.running:
    - enable: True

Or, in a smarter way:

{% set cron = salt['grains.filter_by']({
    'Ubuntu': 'cron',
    'Arch':   'cronie',
    }, grain='os') %}

{{cron}}:
  pkg.installed: []
  service.running:
    - enable: True

Or maybe the service name is different from the package name:

{% set cron = salt['grains.filter_by']({
    'Ubuntu': {
        'package': 'cron',
        'service': 'crond',
        },
    'Arch': {
        'package': 'cronie',
        'service': 'cronie',
        },
    }, grain='os') %}

{{cron['package']}}:
  pkg.installed: []
  service.running:
    - name:   {{cron['service']}}
    - enable: True

grains.filter_by is documented at http://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.grains.html#salt.modules.grains.filter_by

For something more elaborate, take a look at https://github.com/saltstack-formulas/apache-formula/blob/master/apache/map.jinja

Christophe Drevet
  • 1,962
  • 2
  • 17
  • 25