Array

Ansible 將字典轉換為字典/數組的混合

  • April 19, 2022

我使用以下文件:變數文件: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

劇本:劇本.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 的值

例如,

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') }}"

引用自:https://unix.stackexchange.com/questions/699571