Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

以前は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)

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした