【发布时间】:2021-04-29 23:36:44
【问题描述】:
我在 RHEL 7.4 上运行 Ansible 2.7.5。 (我知道它很旧;我会尽快升级——保证)。 zip 功能出现在 Ansible 2.3 中。无论如何,我似乎无法通过 zip 过滤器获得几个列表来正确创建字典。
我从变量文件中读取了列表。该列表是network_interfaces['computer_type'] 在循环中,然后再往下;这是来自调试输出:
[{u'interface': u'bond0.160', u'notes': u'note160'},
{u'interface': u'bond0.197', u'notes': u'note197'},
{u'interface': u'bond1', u'notes': u'bonded, numa1, broadcom device'}]
问题是,我正在尝试将您在上面看到的接口名称连同它们的值一起放入字典中(现在作为示例是“注释”)。但是当我尝试执行dict (_keys|zip(_vals)) 时,如下面_reused_val 的第一个示例所示,我得到了相应的错误消息编号1。因此,为了调试,我重新运行了我的任务,未注释#2,随后使用#3未注释。
- debug:
msg: >
ITEM: {{ item }}
* :::network_interfaces::: {{ network_interfaces[computer_type] }}
* :::_keys::: {{ _keys }}
* :::_vals::: {{ _vals }}
* :::_reused_val::: {{ _reused_val }}
loop: [ " {{ computer_type }} " ]
vars:
computer_type: big_computer
_keys: "{{ network_interfaces[computer_type]|map(attribute='interface')|list }}"
_vals: "{{ network_interfaces[computer_type] }}" # returns a list
_reused_val: "{{ dict(_keys|zip(_vals)) }}" #1
#_reused_val: "{{ _keys|zip(_vals) | list }}" #2
#_reused_val: "{{ _keys|zip(_vals) }}" #3
输出显示reused_val(我稍微调整了间距以使其更易于阅读):
1- "msg": "Unexpected templating type error occurred on ({{ dict(_keys|zip(_vals)) }}): <lambda>() takes exactly 0 arguments (1 given)"
2- [(u'bond0.160', {u'interface': u'bond0.160', u'notes': u'note160'}),
(u'bond0.197', {u'interface': u'bond0.197', u'notes': u'note197'}),
(u'bond1', {u'interface': u'bond1', u'notes': u'bonded, numa1, broadcom device'})]
3- <itertools.izip object at 0x7f311c048dd0>
#1 是我想要开始工作的 - dict(_keys|zip(_vals))。
我不知道为什么#3 显示一个 itertools.izip 对象。我认为它应该返回一个列表。对于#2,我不知道这些括号是干什么用的。是不是因为列表中有 3 个字典?
最后,这里是案例 #3 的完整的 msg 输出;为了更容易阅读,我稍微打断了线条:
"ITEM: big_computer * :::network_interfaces:::
[{u'interface': u'bond0.160', u'notes': u'note160'}, {u'interface': u'bond0.197', u'notes': u'note1
97'}, {u'interface': u'bond1', u'notes': u'bonded, numa1, broadcom device'}]
* :::_keys::: [u'bond0.160', u'bond0.197', u'bond1']
* :::_vals::: [{u'interface': u'bond0.160', u'notes': u'note160'}, {u'interface': u'bond0.197', u'notes': u'note197'}, {u'interface': u'bond1', u'notes': u'bonded, numa1, broadcom device'}]
* :::_reused_val::: <itertools.izip object at 0x7fc768049cb0>\n"
这项工作是我在Ansible: need to combine information from 2 files for a task later 提问的结果 我正在尝试按照示例进行操作,但经过一天的工作,我仍然陷入困境。谢谢。
【问题讨论】: