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

时间:2016-01-07 22:13:03

标签: ansible

我有两个清单:

ForwardIterators

我使用的任务为每个元素获取一些值:

the_list:
  - { name: foo }
  - { name: bar }
  - { name: baz }

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

the_list

一切正常,但是对于许多任务使用- name: Use both shell: do_something {{ item.0.name }} {{ item.1.stdout }} with_together: - "{{ the_list }}" - "{{ spells.results }}" 感到很不舒服,并且将来很难阅读该代码,所以我非常乐意构建{{1从我可以用一个简单的方式使用的那个。让我们这样说:

with_together

这使得这个难题。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

我写了两个ansible过滤器来解决这个问题:zip和todict可以在https://github.com/ahes/ansible-filter-plugins我的回购中找到

样本ansible playbook:

- 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"
        }
    ]
}

答案 1 :(得分:0)

这可能是一种矫枉过正,但您应该尝试编写自定义filter plugin

每次迭代the_list时,您都希望将value添加到dict {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
       }

plugins directory中添加此python代码后,您可以轻松调用foo插件作为参数传递spells列表:

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

相关问题