LoginSignup
1
0

More than 5 years have passed since last update.

Ansibleでネストした辞書のkeyが存在するかチェックする自作フィルター作った

Last updated at Posted at 2018-03-07

以前はwhen: a.b.c is definedで問題なく使用できましたが、Ansibleのバージョン2.0から2.4にあげたらa.bが未定義の場合落ちてしまったので代わりになるフィルターを自分で作ってみました。

とりあえず動かす

サンプルコードを作ったので以下の手順でとりあえず動作確認できます。

git clone https://github.com/ko-he-/ansible_custum_filter_has_nested_keys
cd ansible_custum_filter_has_nested_keys
ansible-playbook test.yaml

使い方

  • ansible.cfgに自作フィルターをディレクトリのパスを書く。
ansible.cfg
[defaults]
filter_plugins=plugin
  • 自作フィルタを配置(plugin/plugin.py)。
plugin/plugin.py

def has_nested_keys(nested_dict, *keys):
    from jinja2.runtime import Undefined
    if isinstance(nested_dict, Undefined):
        return False

    for key in keys:
        if not isinstance(nested_dict, dict):
            return False
        nested_dict = nested_dict.get(key, {})
    return True if nested_dict != {} else False


class FilterModule(object):
    def filters(self):
        return {
            'has_nested_keys': has_nested_keys
}
  • playbookで「has_nested_keys」呼び出す。
    - name: "dict_foo_bar is NOT defined"
      debug: msg="dict_foo2_bar2 is NOT defined"
      when: dict| has_nested_keys('foo2', 'bar2')

dict| has_nested_keys('foo2', 'bar2')dict['foo2']['bar2']が定義されているかをTrue or Falseで返します。(dcitが未定義 or 辞書でない、dict['foo2']が未定義 or 辞書でない場合もFalse)

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