如何将两个列表组合在一起? [英] How to combine two lists together?
问题描述
我有两个列表:
the_list:
- { name: foo }
- { name: bar }
- { name: baz }
我使用了一个任务,它为它的每个元素获取一些价值:
and I use a task which gets some value for its every element:
- name: Get values
shell:
magic_command {{ item.name }}
with_items: the_list
register: spells
从现在开始我可以一起使用 the_list
及其对应的值:
from now on I can use the_list
and its correspondig values together:
- name: Use both
shell:
do_something {{ item.0.name }} {{ item.1.stdout }}
with_together:
- "{{ the_list }}"
- "{{ spells.results }}"
一切正常,但在许多任务中使用 with_together
很不舒服,而且将来很难阅读该代码,所以我非常乐意构建 merged_list代码> 来自我可以以简单方式使用的代码.让我们这样说:
All works fine but it's uncomfortable to use with_together
for many tasks and it'll be hard to read that code in a future so I would be more than happy to build merged_list
from that which I can use in a simple way. Let say something like this:
merged_list:
- { name: foo, value: jigsaw }
- { name: bar, value: crossword }
- { name: baz, value: monkey }
这就是拼图.任何人都可以帮忙吗?
which makes the puzzle. Anyone can help ?
推荐答案
这可能有点矫枉过正,但您应该尝试编写自定义 过滤插件.
It may be an overkill but you should try to write a custom filter plugin.
每次迭代 the_list
时,您都想将 value
添加到该 dict
{name: 'foo'}代码>对吗?
Each time you iterates the_list
you simple wants to add value
to that dict
{name: 'foo'}
right?
更新后,您只希望新 dict 具有如下值:{name: 'foo', value: 'jigsaw'}
After the update you just want that the new dict has the value like: {name: 'foo', value: 'jigsaw'}
过滤器插件非常简单:
def foo(my_list, spells):
try:
aux = my_list
for i in xrange(len(aux)):
my_list[i].update(spells[i])
return my_list
except Exception, e:
raise errors.AnsibleFilterError('Foo plugin error: %s, arguments=%s' % str(e), (my_list,spells) )
class FilterModule(object):
def filters(self):
return {
'foo' : foo
}
在您的插件目录中添加此python代码后,您可以轻松调用 foo
插件,将 spells
列表作为参数传递:
After adding this python code inside your plugins directory, you can easily call the foo
plugin passing the spells
list as a parameter:
- name: Get values
shell:
magic_command {{ item.name }}
with_items: the_list
register: spells
- name: Use both
shell:
do_something {{ item.name }} {{ item.value }}
with_items:
- "{{ the_list | foo(spells.results) }}"
注意:python 代码只是一个示例.阅读有关开发过滤器插件的 ansible 文档.
NOTE: The python code it's just an example. Read the ansible documentations about developing filter plugins.
这篇关于如何将两个列表组合在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!