[英]Problems with Jinja2 and ansible making a sub dict
I need to read a csv file with diferent IPs and make a dictionary with a jinja2 filter for modificate the IP depending the IPNumber value.我需要读取具有不同 IP 的 csv 文件,并使用 jinja2 过滤器制作字典,以便根据 IPNumber 值修改 IP。 The yml file is like:
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
But I get the error:但我收到错误:
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
I know is a syntax problem but I dont guess where the problem is.我知道是语法问题,但我不知道问题出在哪里。
I need some help.我需要帮助。
You should put only variables/expressions within {{
or {%
.您应该只在
{{
或{%
放置变量/表达式。 To me 'Name'
looks like normal text and should be outside.对我来说
'Name'
看起来像普通文本,应该在外面。
Example:例子:
# 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 %}"
This at least should address the error message.这至少应该解决错误消息。
The following task should create your dictionary as per your requirement inside a var you can reuse elsewhere.以下任务应根据您的要求在您可以在其他地方重用的 var 中创建您的字典。 Rename
my_ip_dict
to whatever suits your project better.将
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
Note that I have dropped all the if/else structures by calling directly the correct field depending on IPNumber
.请注意,我通过根据
IPNumber
直接调用正确的字段来删除所有 if/else 结构。 I took for granted it always has a value in the valid scope or the other existing IP*
fields.我认为它总是在有效范围或其他现有
IP*
字段中具有值。 If this is not the case, you can always default that value eg item.value['IP' + item.value.IPNumber] | default('N/A')
如果不是这种情况,您可以始终默认该值,例如
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.