繁体   English   中英

Jinja2 和 ansible 制作子字典的问题

[英]Problems with Jinja2 and ansible making a sub dict

我需要读取具有不同 IP 的 csv 文件,并使用 jinja2 过滤器制作字典,以便根据 IPNumber 值修改 IP。 yml 文件是这样的:

- read_csv:
    path: vms.csv
    key: Number
    fieldnames: Name,IP1,IP2,IP3,IP4,IPNumber 
    delimiter: ';'
  register: vms

- name: vms to dict
  debug:
    msg:
      - {{'Name':{{ item.value.Name }},
          {% if item.value.IPNumber == "1" %}
          'IP':{{ item.value.IP1 }},
          {% endif %}
          {% if item.value.IPNumber ==  "2"%}
          'IP':{{ item.value.IP2 }},
          {% endif %}
          {% if item.value.IPNumber ==  "3"%}
          'IP':{{ item.value.IP3 }},
          {% endif %}
          {% if item.value.IPNumber ==  "4"%}
          'IP':{{ item.value.IP4 }},
          {% endif %}}}
  loop: "{{ vms.dict | dict2items }}"
  register: vms2

但我收到错误:

The error appears to be in '/etc/ansible/roles/vms.yml': line 17, column 16, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

              'Name':{{ item.value.Name}},
              {% if item.value.IPNumber == "1" %}
               ^ here

我知道是语法问题,但我不知道问题出在哪里。

我需要帮助。

您应该只在{{{%放置变量/表达式。 对我来说'Name'看起来像普通文本,应该在外面。

例子:

# Notice the quotes `"` symbol at the beginning and end of debug message

- debug:
    msg:
    - "Name: {{ item.value.Name }},
       {% if item.value.IPNumber == "1" %}
       IP: {{ item.value.IP1 }}
        # and so on... 
       {% endif %}"

这至少应该解决错误消息。

以下任务应根据您的要求在您可以在其他地方重用的 var 中创建您的字典。 my_ip_dict重命名为更适合您项目的名称。

- name: Create my IP dictionary
  set_fact:
    my_ip_dict: >-
      {{
        my_ip_dict | default({})
        | combine({item.value.Name: item.value['IP' + item.value.IPNumber]})
      }}
  loop: "{{ vms.dict | dict2items }}"

- name: Check the result:
  debug:
    var: my_ip_dict

请注意,我通过根据IPNumber直接调用正确的字段来删除所有 if/else 结构。 我认为它总是在有效范围或其他现有IP*字段中具有值。 如果不是这种情况,您可以始终默认该值,例如item.value['IP' + item.value.IPNumber] | default('N/A') item.value['IP' + item.value.IPNumber] | default('N/A')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM