Loops ansible中的多个嵌套循环
我试图循环一个列表,它存储在dict中,它是另一个列表的一部分。我的剧本是这样的:Loops ansible中的多个嵌套循环,loops,ansible,Loops,Ansible,我试图循环一个列表,它存储在dict中,它是另一个列表的一部分。我的剧本是这样的: --- - hosts: all vars: copy_certs: - { domain: 'domainname', copy_to: ['/tmp/foo', '/tmp/bar'], restart: [["mailhost", "postfix"], ["mailhost", "dovecot"]] } - { domain: 'domainname2', copy
---
- 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似乎不支持真正的嵌套,只支持两个嵌套循环的一些预定义结构
我需要类似(不起作用)的东西:
或(子元素的语法错误):
我已经尝试使用冗余列表:
vars:
restart_services:
domainname: [["mailhost", "postfix"]]
tasks:
- name: Debug
debug: var=restart_services[item.item.0.domain]
with_items: copied_key.results
正如您所看到的那样,它已经开始变得丑陋,使用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
而不是元组(实际上是列表)
如果有某种方法可以通过嵌套来指定循环,而不是使用预先制作的过滤器,例如with_subelements
您尝试过使用“with_nested”吗?你可以查一下
这可能会奏效:
- 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
我尝试了
和_nested
,在打开问题之前,对复杂的item.item.item链(可能是中间的索引)得到了类似的奇怪结果。问题是使用嵌套列表的列表,我意识到ansible并不真正支持嵌套列表,但只有一些最常见的嵌套实现(两层,使用哈希,…),但不支持任意嵌套。我还没有测试你的答案,因为我目前以不同的方式解决了这个问题(在运行ansible后使用外部脚本复制内容)。这三个层不在复制部分,而是在重新启动部分,需要嵌套:''''for domain in域中的域:for domain域中的主机。主机:for host中的服务。服务:restart service``。为了避免这些问题,我问题中的示例已经有点扁平化了,但是使用纯ansible来实现这一点仍然很糟糕。除了外部脚本之外的其他可能性可能是使用两个剧本或为ansible编写自定义过滤器,这允许更多嵌套和/或只解决当前用例。
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
- 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