Jinja 条件子句依赖于数据类型

Jinja conditional clause dependent on data type

我正在使用 SaltStack 来管理 BIND9 区域文件。以前我使用过这样的支柱数据:

zones:
  example.com:
    a:
      www1: 1.2.3.4
      www2: 1.2.3.5

连同像这样的神社模板文件(为了便于阅读而缩进):

{% if info.a is defined %}
  {% for host, defn in info.a.items() %}
    {{ host }}  IN  A  {{ defn }}
  {% endfor %}
{% endif %}

其中 info 是上下文变量(zones.example.com 处的字典)。

现在,我需要能够为每个 A 记录定义多个 IP。在前面的示例中,假设我想循环使用子域 www:

zones:
  example.com:
    a:
      www1: 1.2.3.4
      www2: 1.2.3.5
      www:
        - 1.2.3.4
        - 1.2.3.5

这需要 - 在 Jinja 模板中 - 了解 defn 是标量值(表示单个 IP 地址)还是列表(表示 IP 地址集合)之间的区别。类似于:

    {% for host, defn in info.a.items() %}
      {% if DEFN_IS_A_LIST_OBJECT %}
        {% for ip in defn %}
          {{ host }} IN A {{ ip }}
        {% endfor %}
      {% else %}
        {{ host }} IN A {{ defn }}
      {% endif %}
    {% endfor %}

this thread 我试过 if isinstance(defn, list) 但我得到:

Unable to manage file: Jinja variable 'isinstance' is undefined

我也试过 if len(defn) 但我意识到 length() 将对字符串和列表响应 Truthy。它也被报告为错误:

Unable to manage file: Jinja variable 'len' is undefined

如何区分 Jinja 中的列表和字符串?

如果值只能是一个字符串或者一个列表,你可以用builtin test

检查这不是一个字符串
{% if defn is not string %}
    {% for ip in defn %}
        {{ host }} IN A {{ ip }}
    {% endfor %}
{% else %}