LoginSignup
28
24

More than 5 years have passed since last update.

Ansibleの変数(Variables)のマージポリシー

Last updated at Posted at 2015-08-13

Ansibleでvars_filesを並べた時の変数のマージポリシー(hash_behaviour)の話で、デフォルトはreplaceなのですというお話です。

前提

以下のように

  1. vars/base.yml
  2. vars/override.yml

の順に読み込むとしましょう。

site.yml
---
- hosts: all
  vars_files:
    - vars/base.yml
    - vars/override.yml
  tasks:
    - name: "でばっぐ"
      debug: msg="{{ git }}"
vars/base.yml
---
git:
  repo: xxx
  branch: yyyy
vars/override.yml
---
git:
  branch: override

デフォルトの挙動

$ ansible-playbook -i host/local test.yml

PLAY [all] ********************************************************************

GATHERING FACTS ***************************************************************
ok: [127.0.0.1]

TASK: [でばっぐ] **********************************************************
ok: [127.0.0.1] => {
    "msg": "{'branch': 'override'}"
}

おやおや、 git.repo=xxxx が消されてしまいましたね。
replaceのポリシーなので、git というキーの根っこから上書きされ、 git = {branch: override} になってしまいました。

ansible.cfg に hash_behaviour=merge を設定した場合

ansible-playbookコマンドを実行するカレントディレクトリに ansible.cfg ファイルを置いてみましょう。

ansible.cfg
[defaults]
hash_behaviour=merge
$ ansible-playbook -i host/local test.yml

PLAY [all] ********************************************************************

GATHERING FACTS ***************************************************************
ok: [127.0.0.1]

TASK: [でばっぐ] **********************************************************
ok: [127.0.0.1] => {
    "msg": "{'repo': 'xxx', 'branch': 'override'}"
}

git.branch だけが上書きされましたね。

ちなみにansible.cfgファイルは次の順で探されるようです。

  1. カレントディレクトリ
  2. 環境変数の ANSIBLE_CONFIG or ~/ansible.cfg
  3. /etc/ansible/ansible.cfg

See:http://yteraoka.github.io/ansible-tutorial/#test-ansible

28
24
2

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
28
24