目标是遍历包含另一个列表的列表。如果嵌套列表为空,我想改用父级的值。可悲的是我找不到可能的解决方案。
要迭代的列表:
users:
- name: Mario
username: admin_mario
state: present
role: admin
ssh: []
- name: luigi
username: just_luigi
state: present
role: qa
ssh:
- username: qa_luigi
role: qa
state: present
- username: admin_luigi
role: admin
state: present
因此,如果 ssh 为空,我想遍历此列表,使用用户名、状态和角色作为默认值。
- name: test
include_tasks: "mytasks.yml"
loop: "{{ users|subelements(ssh) }}"
loop_control:
loop_var: user
when: users is defined
- name: test
include_tasks: "mytasks.yml"
loop: "{{ users|default({'ssh': [{'username': user.username}]})|subelements('ssh') }}"
loop_control:
loop_var: user
可悲的是,我无法通过 Dokumentation 找到解决方案,例如with_items、循环控制、子元素似乎没有按预期工作。
创建默认值
defaults: "{{ users|json_query('[].{username: username,
state: state,
role: role}') }}"
给予
defaults:
- role: admin
state: present
username: admin_mario
- role: qa
state: present
username: just_luigi
创建 ssh 列表
ssh_str: |
{% for i,j in users|zip(defaults) %}
{% if i.ssh|length == 0 %}
- ssh: [{{ j }}]
{% else %}
- ssh: {{ i.ssh }}
{% endif %}
{% endfor %}
ssh: "{{ ssh_str|from_yaml }}"
给予
ssh:
- ssh:
- role: admin
state: present
username: admin_mario
- ssh:
- role: qa
state: present
username: qa_luigi
- role: admin
state: present
username: admin_luigi
合并列表中的项目
- debug:
msg: "{{ item.0.name }} {{ item.1.username }} {{ item.1.role }} {{ item.1.state }}"
with_subelements:
- "{{ users|zip(ssh)|map('combine') }}"
- ssh
给(删节)
msg: Mario admin_mario admin present
msg: luigi qa_luigi qa present
msg: luigi admin_luigi admin present
完整的 teting 剧本示例
- hosts: localhost
vars:
users:
- name: Mario
username: admin_mario
state: present
role: admin
ssh: []
- name: luigi
username: just_luigi
state: present
role: qa
ssh:
- username: qa_luigi
role: qa
state: present
- username: admin_luigi
role: admin
state: present
defaults: "{{ users|json_query('[].{username: username,
state: state,
role: role}') }}"
ssh_str: |
{% for i,j in users|zip(defaults) %}
{% if i.ssh|length == 0 %}
- ssh: [{{ j }}]
{% else %}
- ssh: {{ i.ssh }}
{% endif %}
{% endfor %}
ssh: "{{ ssh_str|from_yaml }}"
tasks:
- debug:
var: defaults
- debug:
var: ssh
- debug:
msg: "{{ item.0.name }} {{ item.1.username }} {{ item.1.role }} {{ item.1.state }}"
with_subelements:
- "{{ users|zip(ssh)|map('combine') }}"
- ssh