问题描述
我很难理解 ansible with_subelements 语法的逻辑,with_subelements 到底是做什么的?我在这里查看了关于 with_subelements 的 ansible 文档https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html#with-subelements 并没有太大帮助.我还在博客上看到了一个带有 with_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 https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html#with-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
Task List 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
(在我的例子中是family)是一个外部项目,而item.1
(在我的例子中是child)是一个内部项目.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!