jinja在/ etc / hosts的salt file.blockreplace中循环

时间:2018-07-13 14:20:27

标签: ldap jinja2 salt

盐状态下的jinja代码出现了一些问题,应该通过LDAP支柱更改/ etc / hosts文件。

    {% 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

LDAP支柱采用以下格式:

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

现在,我想捕获所有IP和主机名,以构建有效的主机文件。

这是我的错误:

    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
    [...]
    ---

1 个答案:

答案 0 :(得分:0)

我只是固定住了。很安静。

{% 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

现在一切正常。