簡體   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