Ansible中的多个嵌套循环

Ansible中的多个嵌套循环

本文介绍了Ansible中的多个嵌套循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图遍历一个存储在字典中的列表,该字典是另一个列表的一部分.我的剧本看起来像这样:

I am trying to loop over a list, which is stored in a dict, which is part of another list. my playbook looks like this:

---
- hosts: all
  vars:
    copy_certs:
      - { domain: 'domainname', copy_to: ['/tmp/foo', '/tmp/bar'], restart: [["mailhost", "postfix"], ["mailhost", "dovecot"]] }
      - { domain: 'domainname2', copy_to: ['/tmp/foo2', '/tmp/bar2'], restart: [["mail.lxc", "postfix"]] }
  tasks:
[...]
    - name: Copy Private Key
      register: copied_key
      copy: src=/etc/letsencrypt/live/{{ item.0.domain }}/privkey.pem dest="{{ item.1 }}/"
      with_subelements:
        - copy_certs
        - copy_to
    - name: Debug (here should be delegates to "item.restart.NUM.0" to restart "item.restart.NUM.1" with_subelements: ...)
      debug: var=item
      with_items: copied_key.results

现在,我正在反复遍历列表,因为ansible似乎不支持真正的嵌套,而只是为两个嵌套循环提供了一些预定义的结构.

Now i am stack at iterating over the lists, as ansible seems not to support real nesting, but just a few predefined structures for two nested loops.

我需要类似的东西(不起作用):

i would need something like (does not work):

with_subelements:
  - copied_key.results
  - item.domain.restart

或(子元素的语法错误):

or (wrong syntax for subelements):

with_subelements:
  - copied_key.results
  - item.domain
  - restart

我已经尝试使用冗余列表:

I already tried to use an redundant list:

vars:
  restart_services:
    domainname: [["mailhost", "postfix"]]
tasks:
  - name: Debug
  debug: var=restart_services[item.item.0.domain]
  with_items: copied_key.results

如您所见,item.item已经开始变得丑陋.

as you see it already starts being ugly with item.item.

它需要类似

  register: [to_restart for to_restart in item['restart']] as services_to_rstart
- debug: var=item # item.0 = hostname item.1 = servicename
  with_items: services_to_restart

,或者如果不需要列表就可以在item.hostname上遍历它,而不是元组(实际上是列表).

or if it does not need to be lists to be able to iterate over it even item.hostname instead of tuples (actually lists).

有某种方法可以指定嵌套嵌套循环,而不是使用像with_subelements这样的预制过滤器.

It would be really good to have some way to specify loops with nesting instead of using premade filters like with_subelements.

推荐答案

您是否尝试过使用"with_nested"?您可以查看 Ansible文档.

Have you tried using "with_nested"? You can check out the Ansible documentation.

这可能有效:

- name: Copy Private Key
  register: copied_key
  copy: src=/etc/letsencrypt/live/{{ item[0].domain }}/privkey.pem dest="{{ item[1] }}/"
  with_nested:
    - copy_certs
    - copy_certs.copy_to

这篇关于Ansible中的多个嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:23