遍历多个字典列表 – Ansible

huangapple go评论66阅读模式
英文:

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."

huangapple
  • 本文由 发表于 2023年6月22日 16:16:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76529850.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定