Search code examples
jinja2salt-project

SaltStack check if grain exists in Jinja file


I'm using SaltStack to manage my infra. Machines are hosted in different DCs, so they also have slightly different network setup. Currently, I'm running into the following issue:

Comment: Unable to manage file: Jinja variable 'dict object' has no attribute 'macaddress'; line 9
              
              ---
              [...]
                ethernets:
                  {{ grains['interface_context'] }}:
                    dhcp4: {{ grains['dhcp4'] }}
                    dhcp6: {{ grains['dhcp6'] }}
                    addresses: [{{ grains['ipv4'] }}, "{{ grains['ipv6'] }}"]
                    {% if grains['macaddress'] %}    <======================
                    match:
                        macaddress: {{ grains['macaddress'] }}
                    {% endif %}
                    routes:
                      - to: default
              [...]
              ---

As the message indicates, the grain "macaddress" is missing, which I can confirm, it's not set for this minion. But What I do not understand is how I can simply check if this variable/grain exists at all within a jinja template? I wouldn't expect this error to come up, as I actually wanted to catch it with the if statement.

Can somebody help?


Solution

  • Use get to return None instead of raising:

    {% if grains.get('macaddress') is not none %}
    

    Or if you want to treat "empty" values the same:

    {% if not grains.get('macaddress') %}