1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

YAMLで階層化した値を部分上書き(combine)

1
Posted at

YAMLで階層化した値を部分上書きだるいなぁと思って調べてたら combine が良さそうだったのでメモ。

確認環境

ansible-core v2.19.9

お試し結果

var_combine.yaml

- hosts: localhost
  gather_facts: false

  vars:
    app_default:
      db:
        host: db1
        port: 5432

    app_override:
      db:
        host: db2

    app_extra:
      db:
        port: 5433

  tasks:
  - name: merge A + B
    ansible.builtin.set_fact:
      app_tmp: "{{ app_default | combine(app_override, recursive=True) }}"

  - name: merge + C
    ansible.builtin.set_fact:
      app: "{{ app_tmp | combine(app_extra, recursive=True) }}"

  - name: debug
    ansible.builtin.debug:
      var: app

実行してみる。

app_default に app_override と app_extra を上書きしているのが分かる。

$ uv run ansible-playbook -v -i localhost, var_combine.yaml
Using /etc/ansible/ansible.cfg as config file

PLAY [localhost] *******************************************************************************************************************************

TASK [merge A + B] *****************************************************************************************************************************
ok: [localhost] => {"ansible_facts": {"app_tmp": {"db": {"host": "db2", "port": 5432}}}, "changed": false}

TASK [merge + C] *******************************************************************************************************************************
ok: [localhost] => {"ansible_facts": {"app": {"db": {"host": "db2", "port": 5433}}}, "changed": false}

TASK [debug] ***********************************************************************************************************************************
ok: [localhost] => {
    "app": {
        "db": {
            "host": "db2",
            "port": 5433
        }
    }
}

PLAY RECAP *************************************************************************************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

おまけ:まとめてやりたい場合

| で繋いでやれば良い。

  - name: merge + A + B + C
    ansible.builtin.set_fact:
      app2: "{{ app_default | combine(app_override, recursive=True) | combine(app_extra, recursive=True) }}"
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?