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

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

我需要一些帮助。

您应该只将 variables/expressions 放在 {{{% 中。对我来说 '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')