Ansible 循环子项目

问题描述 投票:0回答:1

我很难循环 jinja 文件中的子变量

现在我已经在我的 jinja 文件中得到了这个:

{% for item in rsyslog_custom_templates.name %}
$template "{{ item.1.template_tag }}","{{ item.1.template_dir }}"
if $syslogtag == "{{ item.1.template_tag }}" then -?"{{ item.1.template_tag }}"
{% endfor %}

与 item.1 配合不好

在我的group_vars中:

rsyslog_custom_templates:
 name: 
   projet1:
     - template_tag: "log1"
       template_dir: "/dir1"
     - template_tag: "log2"
       template_dir: "/dir2"
   projet2:
     - template_tag: "log1"
       template_dir: "/dir1"

我想循环每个项目名称中的 var 并从中创建唯一的文件,如果您对此有任何建议!

我希望有:

projet1.conf 文件:

$template log1,/dir1
if $syslogtag == log1 then -?log1
$template log2,/dir2
if $syslogtag == log2 then -?log2

projet2.conf 文件:

$template log1,/dir1
if $syslogtag == log1 then -?log1

谢谢!

for-loop ansible jinja2
1个回答
0
投票

例如,

    - copy:
        dest: "/tmp/{{ item.key }}.conf"
        content: |
          {% for j in item.value %}
          $template {{ j.template_tag }},{{ j.template_dir }}
          if $syslogtag == {{ j.template_tag }} then -?{{ j.template_tag }}
          {% endfor %}
      loop: "{{ rct.name|dict2items }}"

给你想要的东西

shell> cat /tmp/projet1.conf 
$template log1,/dir1
if $syslogtag == log1 then -?log1
$template log2,/dir2
if $syslogtag == log2 then -?log2
shell> cat /tmp/projet2.conf 
$template log1,/dir1
if $syslogtag == log1 then -?log1

用于测试的完整剧本示例

- hosts: all

  vars:

    rct:
      name: 
        projet1:
          - template_tag: "log1"
            template_dir: "/dir1"
          - template_tag: "log2"
            template_dir: "/dir2"
        projet2:
          - template_tag: "log1"
            template_dir: "/dir1"

  tasks:

    - copy:
        dest: "/tmp/{{ item.key }}.conf"
        content: |
          {% for j in item.value %}
          $template {{ j.template_tag }},{{ j.template_dir }}
          if $syslogtag == {{ j.template_tag }} then -?{{ j.template_tag }}
          {% endfor %}
      loop: "{{ rct.name|dict2items }}"
© www.soinside.com 2019 - 2024. All rights reserved.