英文:
Iterate multiple list of dictionary - Ansible
问题
我想使用loop
语句迭代多个字典列表,此处为两个。
变量:
my_team:
- { name: 'testuser1', groups: 'wheel' }
- { name: 'testuser2', groups: 'root' }
your_team:
- { name: 'testuser3', groups: 'wheel' }
- { name: 'testuser4', groups: 'root' }
代码:
- name: 添加多个用户
ansible.builtin.user:
name: "{{ item.name }}"
state: present
groups: "{{ item.groups }}"
loop:
- "{{ my_team }}"
- "{{ your_team }}"
我相信在列表前面加上破折号(-
)会将它们变成嵌套列表,但这也会使代码更易阅读。唯一的解决方法是在loop
部分内部将它们展平,还是应该尝试合并它们?
英文:
I want to iterate through multiple, in this case two, lists of dictionary using the loop
statement.
Variables:
my_team:
- { name: 'testuser1', groups: 'wheel' }
- { name: 'testuser2', groups: 'root' }
your_team:
- { name: 'testuser3', groups: 'wheel' }
- { name: 'testuser4', groups: 'root' }
Code:
- name: Add several users
ansible.builtin.user:
name: "{{ item.name }}"
state: present
groups: "{{ item.groups }}"
loop:
- "{{ my_team }}"
- "{{ your_team }}"
I believe using the dash (-
) followed by the list will make it a nested list, but also makes the code more readable. Is the only solution to flatten them in the loop
section itself, or should I try to merge both of them?
答案1
得分: 2
- name: 添加多个用户
ansible.builtin.user:
name: "{{ item.name }}"
state: present
groups: "{{ item.groups }}"
loop: "{{ my_team|d([], true) + your_team|d([], true) }}"
Q: "它是否还可以处理空列表或NoneType类型的空变量,默认为使用空列表吗?"
A: 可以。它可以。请参阅过滤器default
"如果要对评估为假的变量使用默认值,必须将第二个参数设置为true。"
英文:
You can add the lists
- name: Add several users
ansible.builtin.user:
name: "{{ item.name }}"
state: present
groups: "{{ item.groups }}"
loop: "{{ my_team|d([], true) + your_team|d([], true) }}"
Q: "Could it also handle empty lists, or empty variables of type NoneType by defaulting to empty lists?"
A: Yes. It can. See the filter default
> "If you want to use default with variables that evaluate to false you have to set the second parameter to true."
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论