LoginSignup
7
10

More than 5 years have passed since last update.

Ansibleで必須でないパラメータ未定義時のエラーを回避する

Last updated at Posted at 2017-05-15

はじめに

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

これでエラーになることなくインストールが成功します。

7
10
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
7
10