はじめに
Ansibleのモジュールには、必須パラメータと必須でないパラメータがあります。
同じモジュールを利用する場合でも、要件により必須でないパラメータを定義あるいは省略したいケースがありますが、playbookで定義したパラメータにはなんらかの値を渡してやらないと下記のようなエラーが出てfailしてしまいます。
エラー
"msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'dict object' has no attribute 'version'
Example
pipモジュールでpythonモジュールをインストールする場合を考えてみます。
pipモジュールには下記のようなパラメータがあります(一部のみ抜粋)。
- name(必須)
- version(任意)
ここで、以下のような変数とplaybookで複数のpythonモジュールをインストールしてみます。
vars
---
my_vars:
middlewares:
python:
modules:
- name: ansible
version: 2.2.0.0
- name: awscli #バージョン指定なし
playbook
---
- name: install python modules
pip:
name: "{{ item.name }}"
version: "{{ item.version }}"
state: present
with_items: "{{ my_vars.middlewares.python.modules }}"
しかし、バージョンを定義しているAnsibleは正常にインストールされますが、バージョン未定義のawscliは下記のようにエラーになってしまいます。
エラー
"msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'dict object' has no attribute 'version'
Solution
| default(omit)
を使う
必須でないパラメータに| default(omit)
をつけることで、値が未定義の際のエラーを抑止できます。
playbook(new)
---
- name: install python modules
pip:
name: "{{ item.name }}"
version: "{{ item.version | default(omit) }}"
state: present
with_items: "{{ my_vars.middlewares.python.modules }}"
これでエラーになることなくインストールが成功します。