ansible 中的多个嵌套循环 [英] Multiple nested loops in ansible

查看:67
本文介绍了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 中的多个嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆