【问题标题】:Problems with Jinja2 and ansible making a sub dictJinja2 和 ansible 制作子字典的问题
【发布时间】:2020-09-28 11:36:50
【问题描述】:

我需要读取具有不同 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

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

我需要一些帮助。

【问题讨论】:

    标签: ansible yaml jinja2


    【解决方案1】:

    以下任务应根据您的要求在您可以在其他地方重用的 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')

    【讨论】:

      【解决方案2】:

      您应该只将变量/表达式放在{{{% 中。对我来说'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 %}"
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-07
        • 1970-01-01
        • 2020-01-16
        • 2021-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多