Search code examples
ldapjinja2salt-project

jinja for loop in salt file.blockreplace for /etc/hosts


I have some issues with my jinja code inside my salt state, which should change the /etc/hosts file by a LDAP Pillar.

    {% set CID = grains['CID'] %}
    {% set ldap_pillar = 'ldap-hosts-{{CID}}' %}

    ldap-hosts:
        file.blockreplace:
            - name: /tmp/hosts
            - marker_start: "# BEGIN SALT MANAGED CONTENT - DO NOT EDIT BETWEEN THIS - #"
            - marker_end: "# END SALT MANAGED CONTENT - DO NOT EDIT BETWEEN THIS - #"
            - content:
                {% for entry in {{ salt.pillar.get('ldap_pillar') }} %}
                    {% for hostname, ip in entry.items %}
                        {{ip}}  {{hostname}}
                    {% endfor %}
                {% endfor %}
            - show_changes: True
            - append_if_not_found: True

The LDAP Pillar serves the following Format:

    local:
        |_
          ----------
          cn:
              host1.domain.tld
          ipHostNumber:
              4.4.4.4
        |_
          ----------
          cn:
              host2
          ipHostNumber:
              8.8.8.8

Now I like to catch all the IPs and Hostnames a build a valid host file.

Here is my Error:

    local:
        Data failed to compile:
    ----------
        Rendering SLS 'base:ldap_hosts' failed: Jinja syntax error: expected token ':', got '}'; line 10

    ---
    [...]
        file.blockreplace:
            - name: /tmp/hosts
            - marker_start: "# BEGIN SALT MANAGED CONTENT - DO NOT EDIT BETWEEN THIS - #"
            - marker_end: "# END SALT MANAGED CONTENT - DO NOT EDIT BETWEEN THIS - #"
            - content:
                {% for entry in {{ salt.pillar.get('ldap_pillar') }} %}    <======================
                    {% for hostname, ip in entry.items %}
                        {{ip}}  {{hostname}}
                    {% endfor %}
                {% endfor %}
            - show_changes: True
    [...]
    ---

Solution

  • I just fiexed it. It was quiet easy.

    {% set CID = grains['CID'] %}
    {% set ldap_pillar = 'ldap-hosts-'+CID %}
    
    ldap-hosts:
        file.blockreplace:
            - name: /etc/hosts
            - marker_start: "# BEGIN SALT MANAGED CONTENT - DO NOT EDIT BETWEEN THIS - #"
            - marker_end: "# END SALT MANAGED CONTENT - DO NOT EDIT BETWEEN THIS - #"
            - content: |
                {% for entry in salt['pillar.get'](ldap_pillar) -%}
                    {{entry.ipHostNumber}}  {{entry.cn}}
                {% endfor %}
            - show_changes: True
            - append_if_not_found: True
    

    Now everything worked good.