在 Ansible 模板中使用变量

Use variable in Ansible template

我需要通过 jinja 模板创建一个文件,但遇到了一些问题。

我的变量

my:
  acl:
        - name: test
          allow:
            - 0.0.0.0
          deny:
            - 1.1.1.1
        - name: china
          allow:
            - 1.2.3.4
          deny:
            - 10.10.10.10

我的任务:

- name: Create acl file
  template:
    force: yes
    src: acl.conf.j2
    dest: "/etc/nginx/conf.d/{{ item.name }}.conf"
  become: yes
  with_items:
    - "{{ my.acl }}"

我的模板

{% for allow in my.acl %}
allow {{allow.allow}};
{% endfor %}
{% for deny in my.acl %}
deny {{deny.deny}};
{% endfor %}

结果china.conf

allow ['0.0.0.0'];
allow ['1.2.3.4'];
deny ['1.1.1.1'];
deny ['10.10.10.10'];

结果test.conf

allow ['0.0.0.0'];
allow ['1.2.3.4'];
deny ['1.1.1.1'];
deny ['10.10.10.10'];

我只需要 china 文件中对象 china 中定义的 ip 地址,而不需要 [' ']

我该怎么做?

添加一个 if 并打印 allowdeny 列表中的第一个对象:

{% for allow in my.acl %}
  {% if allow.name == 'china' %}
    allow {{ allow.allow[0] }};
  {% endif %}
{% endfor %}
{% for deny in my.acl %}
  {% if allow.name == 'china' %}
    deny {{ deny.deny[0] }};
  {% endif %}
{% endfor %}

如果允许和拒绝列表将包含多个元素,请使用此:

{% for allow in my.acl %}
  {% if allow.name == 'china' %}
    {% for ip in allow.allow %}
      allow {{ ip }};
    {% endfor %}
  {% endif %}
{% endfor %}
{% for deny in my.acl %}
  {% if deny.name == 'china' %}
    {% for ip in deny.deny %}
      deny {{ ip }};
    {% endfor %}
  {% endif %}
{% endfor %}

修复模板

{% for allow in item.allow %}
allow {{ allow }};
{% endfor %}
{% for deny in item.deny %}
deny {{ deny }};
{% endfor %}