Ansible

Ansible:如何更新文件中的目錄值

  • March 18, 2022

我使用以下內容:

目錄文件:dir.yml

x86_64:
 alpine:
   update:
   version: 3.14.0

aarch64:
 alpine:
   update:
   version: 3.14.0 

可靠的劇本:

---
- name: Playbook  
 hosts: localhost

 vars:
   new_version: 3.15.0
   update:

 tasks:
 
   - name: "Include: dir.yml"
     ansible.builtin.include_vars:
       file: dir.yml
   
   - debug:
       msg: 
         - "{{x86_64.alpine.version}}"
         - "{{new_version}}"
         - "{{update}}"
   
   - set_fact:
       update: "{{'true' if x86_64.alpine.version < new_version else 'false'}}"

問題:

如何更新 dir.yml 中的以下欄位

x86_64:
 alpine:
   update: true <------

我試圖使用 ansible.builtin.replace 或 ansible.builtin.lineinfile 但仍然無法弄清楚

有沒有人對此有任何解決方案

將文件讀入字典

   - ansible.builtin.include_vars:
       file: dir.yml
       name: arch

 arch:
   aarch64:
     alpine:
       update: null
       version: 3.14.0
   x86_64:
     alpine:
       update: null
       version: 3.14.0

更新字典

   - ansible.builtin.set_fact:
       arch: "{{ arch|combine({'x86_64': _x86_64}) }}"
     vars:
       _update: "{{ arch.x86_64.alpine.version is version(new_version, '<') }}"
       _x86_64_alpine: "{{ arch.x86_64.alpine|combine({'update': _update}) }}"
       _x86_64: "{{ arch.x86_64|combine({'alpine': _x86_64_alpine}) }}"

 arch:
   aarch64:
     alpine:
       update: null
       version: 3.14.0
   x86_64:
     alpine:
       update: true
       version: 3.14.0

並重寫文件

   - ansible.builtin.copy:
       dest: dir.yml
       content: |-
         {% for k,v in arch.items() %}
         {{ k }}:
           {{ v|to_nice_yaml }}
         {% endfor %}

shell> cat dir.yml
x86_64:
 alpine:
   update: true
   version: 3.14.0

aarch64:
 alpine:
   update: null
   version: 3.14.0

筆記

  • 屬性更新的空值將被“null”替換。這應該不是問題,因為“null”在 YAML 中轉換為布爾值“false”。
  • 更新後的屬性update的值將替換為“true”或“false”。
  • 由於前兩個註釋,這些任務是冪等的。
  • 您可能想要更新更多項目。例如,給定變數
   new_version:
     x86_64: 3.15.0
     aarch64: 3.14.0

下面的任務更新字典

   - ansible.builtin.set_fact:
       arch: "{{ arch|combine({item: _arch}) }}"
     loop: "{{ new_version.keys()|list }}"
     vars:
       _update: "{{ arch[item].alpine.version is version(new_version[item], '<') }}"
       _arch_alpine: "{{ arch[item].alpine|combine({'update': _update}) }}"
       _arch: "{{ arch[item]|combine({'alpine': _arch_alpine}) }}"

 arch:
   aarch64:
     alpine:
       update: false
       version: 3.14.0
   x86_64:
     alpine:
       update: true
       version: 3.14.0

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