Ansible 如何将两个列表组合在一起?

Ansible 如何将两个列表组合在一起?,ansible,Ansible,我有两份清单: the_list: - { name: foo } - { name: bar } - { name: baz } 我使用一个任务,它的每个元素都有一些值: - name: Get values shell: magic_command {{ item.name }} with_items: the_list register: spells 从现在起,我可以将_列表及其对应的IG值一起使用: - name: Use both shell:

我有两份清单:

the_list:
  - { name: foo }
  - { name: bar }
  - { name: baz }
我使用一个任务,它的每个元素都有一些值:

- name: Get values
  shell:
    magic_command {{ item.name }}
  with_items: the_list
  register: spells
从现在起,我可以将_列表及其对应的IG值一起使用:

- name: Use both
  shell:
    do_something {{ item.0.name }} {{ item.1.stdout }}
  with_together:
    - "{{ the_list }}"
    - "{{ spells.results }}"
所有这些都可以正常工作,但是将
与_一起用于许多任务会让人感到不舒服,而且将来很难阅读这些代码,因此我非常乐意以一种简单的方式构建
合并的_列表
。比如说:

merged_list:
 - { name: foo, value: jigsaw }
 - { name: bar, value: crossword }
 - { name: baz, value: monkey }

这就是谜题。有人可以帮忙吗?

这可能有点过分,但你应该试着编写一个自定义

每次你迭代
这个列表
的时候,你都想把
加到
目录
{name:'foo'}
上,对吗

更新后,您只希望新的dict具有如下值:
{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
插件,并将
拼写列表作为参数传递:

 - 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文档。

我写了两个ansible过滤器来解决这个问题:zip和todict,可在我的repo中找到

ansible剧本示例:

- hosts: localhost
  vars:
    users:
      - { name: user1 }
      - { name: user2 }
  tasks:
    - name: Get uids for users
      command: id -u {{ item.name }}
      register: uid_results
      with_items: users

    - set_fact:
        uids: "{{ uid_results.results | map(attribute='stdout') | todict('uid') }}"

    - set_fact:
        users: "{{ users | zip(uids) }}"

    - name: Show users with uids
      debug: var=users
结果将是:

TASK [Show users with uids] ****************************************************
ok: [localhost] => {
    "users": [
        {
            "name": "user1",
            "uid": "1000"
        },
        {
            "name": "user2",
            "uid": "2000"
        }
    ]
}