问题描述
我很难理解ansible with_subelements语法的逻辑,with_subelements到底能做什么?我在这里查看了有关with_subelements的ansible文档 http://docs.ansible .com/ansible/playbooks_loops.html#looping-over-subelements ,效果不是很好.我还在博客
I am having a hard time understanding the logic of ansible with_subelements syntax, what exactly does with_subelements do? i took a look at ansible documentation on with_subelements here http://docs.ansible.com/ansible/playbooks_loops.html#looping-over-subelements and was not very helpful. I also saw a playbook with with_subelements example on a blog
---
- hosts: cent
vars:
users:
- name: jagadish
comments:
- 'Jagadish is Good'
- name: srini
comments:
- 'Srini is Bad'
tasks:
- name: User Creation
shell: useradd -c "{{ item.1 }}" "{{ item.0.name }}"
with_subelements:
- users
- comments
item.1和item.0分别指什么?
what do item.1 and item.0 refer to?
推荐答案
这是subelements
查找工作原理的一个非常糟糕的例子. (并且还有旧的,不受支持的语法).
This is really bad example of how subelements
lookup works. (And has old, unsupported, syntax as well).
看看这个:
---
- hosts: localhost
gather_facts: no
vars:
families:
- surname: Smith
children:
- name: Mike
age: 4
- name: Kate
age: 7
- surname: Sanders
children:
- name: Pete
age: 12
- name: Sara
age: 17
tasks:
- name: List children
debug:
msg: "Family={{ item.0.surname }} Child={{ item.1.name }} Age={{ item.1.age }}"
with_subelements:
- "{{ families }}"
- children
任务列出子项就像一个嵌套循环,遍历families
列表(外循环)和每个族中的children
子元素(内循环).
因此,您应该提供一个字典列表作为subelements
的第一个参数,以及要在每个外部项目中迭代的子元素的名称.
Task List children is like a nested loop over families
list (outer loop) and over children
subelement in each family (inner loop).
So you should provide a list of dicts as first argument to subelements
and name of subelement you want to iterate inside each outer item.
通过这种方式,item.0
(在我的示例中为家庭)是外部项目,而item.1
(在我的示例中为子级)是内部项目.
This way item.0
(family in my example) is an outer item and item.1
(child in my example) is an inner item.
在Ansible文档示例中,subelements
用于循环用户(外部)并添加多个公共密钥(内部).
In Ansible docs example subelements
is used to loop over users (outer) and add several public keys (inner).
这篇关于Ansible with_subelements的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!