我使用以下文件:变量文件:db.yml
x86_64:
alpine:
version: 3.15.0
debian:
version: 11.3.0
aarch64:
alpine:
version: 3.15.0
debian:
version: 11.3.0
剧本:playbook.yml
---
- name: "Playbook"
hosts: localhost
connection: local
gather_facts: no
tasks:
- name: Import variables
ansible.builtin.include_vars:
file: db.yml
name: db
- name: DENUG >>> db
debug:
var: db
- name: DENUG >>> db
debug:
var: db[item].alpine
loop: "{{ db.keys()|list }}"
when: db[item].alpine is defined
输出:
ok: [localhost] => (item=x86_64) => {
"ansible_loop_var": "item",
"db[item].alpine": {
"version": "3.15.0"
},
"item": "x86_64"
}
ok: [localhost] => (item=aarch64) => {
"ansible_loop_var": "item",
"db[item].alpine": {
"version": "3.15.0"
},
"item": "aarch64"
}
现在我已将 db.yml 转换为新样式,如下所示:
x86_64:
- distribution: alpine
version: 3.15.0
- distribution: debian
version: 11.3.0
aarch64:
- distribution: alpine
version: 3.15.0
- distribution: debian
version: 11.3.0
问题:
如何运行类似的命令如下:
- name: DENUG >>> db
debug:
var: db[item].alpine
loop: "{{ db.keys()|list }}"
when: db[item].alpine is defined
并获得与输出中可用的结果相同的结果。
基本上如何循环通过这个新的 db.yml 来获取 db.x86_64.alpine.version 的值
答案1
例如,
db_list: "{{ dict(_keys|zip(_vals)) }}"
_keys: "{{ db.keys()|list }}"
_vals: "{{ db.values()|map('dict2items')|map('json_query', _query) }}"
_query: "[].{distribution: key, version: value.version}"
给出
db_list:
aarch64:
- distribution: alpine
version: 3.15.0
- distribution: debian
version: 11.3.0
x86_64:
- distribution: alpine
version: 3.15.0
- distribution: debian
version: 11.3.0
通常,创建一个包含所有属性的列表
db_list: "{{ _val2|zip(_val1)|
map('flatten')|
map('zip', ['version', 'arch', 'distribution'])|
map('map', 'reverse')|
map('community.general.dict') }}"
_dict: "{{ lookup('ansible.utils.to_paths', db) }}"
_val1: "{{ _dict.keys()|map('split', '.')|list }}"
_val2: "{{ _dict.values()|list }}"
给出
db_list:
- arch: x86_64
distribution: alpine
version: 3.15.0
- arch: x86_64
distribution: debian
version: 11.3.0
- arch: aarch64
distribution: alpine
version: 3.15.0
- arch: aarch64
distribution: debian
version: 11.3.0
现在,您可以选择您想要的任何内容,例如
- 迭代架构的子集
- debug:
msg: "{{ item }}"
loop: "{{ db_list|selectattr('arch', 'in', ['aarch64', 'x86_64']) }}"
- 迭代发行版“debian”
- debug:
msg: "{{ item }}"
loop: "{{ db_list|selectattr('distribution', 'eq', 'debian') }}"
- 迭代小于“11.3.0”的版本
- debug:
msg: "{{ item }}"
loop: "{{ db_list|selectattr('version', 'version', '11.3.0', '<') }}"
- 在架构“aarch64”中迭代分布“alpine”
- debug:
msg: "{{ item }}"
loop: "{{ db_list|selectattr('arch', 'eq', 'aarch64')|
selectattr('distribution', 'eq', 'alpine') }}"