Ansible: ファイルのディレクトリ値を更新する方法

Ansible: ファイルのディレクトリ値を更新する方法

私は使用します:
ディレクトリファイル:dir.yml

x86_64:
  alpine:
    update:
    version: 3.14.0

aarch64:
  alpine:
    update:
    version: 3.14.0 

Ansible プレイブック:

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

Q:
dir.ymlで次のフィールドを更新する方法

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

ansible.builtin.replaceまたはansible.builtin.lineinfileを使用しようとしましたが、まだわかりません。

誰にも解決策はありますか?

ベストアンサー1

辞書でファイルを読む

    - 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では、 "null"がブール値 "false"に変換されるため、これは問題になりません。

  • 属性値の更新修正する「true」または「false」に置き換えられます。

  • 最初の 2 つのコメントのため、これらの操作は冪等性を持ちます。

  • より多くの項目を更新したい場合があります。たとえば、変数が与えられた場合

    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

おすすめ記事