0

アドホックな ansible コマンドの JSON 出力をフィルタリングしたいと思います。たとえば、複数のホストの「ファクトansible_lsb.description」の長いリストを取得し、いくつかのレベルの深さの可能性のある 1 つだけを表示して、バージョンをすばやく比較できるようにします。実行中のソフトウェアの正確な時刻やタイムゾーンなどを確認します。

これは機能します:

ansible myserver -m setup -a 'filter=ansible_lsb'
myserver | SUCCESS => {
    "ansible_facts": {
        "ansible_lsb": {
            "codename": "wheezy",
            "description": "Debian GNU/Linux 7.11 (wheezy)",
            "id": "Debian",
            "major_release": "7",
            "release": "7.11"
        }
    },
    "changed": false
}

ただし、セットアップモジュールのドキュメントに記載されているように、「フィルターオプションは ansible_facts の下の最初のレベルのサブキーのみをフィルター処理する」ため、これは失敗します。

ansible myserver -m setup -a 'filter=ansible_lsb.description'
myserver | SUCCESS => {
    "ansible_facts": {},
    "changed": false
}

(参考までに、タスクのwhen conditionalなどの他の場所でドット表記を使用できます)

出力が表示される前に JSON キーをフィルタリングする方法はありますか?

4

1 に答える 1

2

標準setupモジュールは、「トップレベル」のファクトにのみフィルターを適用できます。

setup目的を達成するために、カスタム フィルターを適用する名前の付いたアクション プラグインを作成できます。

作業例./action_plugins/setup.py:

from ansible.plugins.action import ActionBase

class ActionModule(ActionBase):

    def run(self, tmp=None, task_vars=None):

        def lookup(obj, path):
            return reduce(dict.get, path.split('.'), obj)

        result = super(ActionModule, self).run(tmp, task_vars)

        myfilter = self._task.args.get('myfilter', None)

        module_args = self._task.args.copy()
        if myfilter:
            module_args.pop('myfilter')

        module_return = self._execute_module(module_name='setup', module_args=module_args, task_vars=task_vars, tmp=tmp)

        if not module_return.get('failed') and myfilter:
            return {"changed":False, myfilter:lookup(module_return['ansible_facts'], myfilter)}
        else:
            return module_return

元のsetupモジュールの strippingmyfilterパラメータを呼び出し、タスクが失敗せず、myfilter が設定されている場合、単純な reduce 実装で結果をフィルタリングします。検索機能は非常に単純なので、リストでは機能せず、オブジェクトのみで機能します。

結果:

$ ansible myserver -m setup -a "myfilter=ansible_lsb.description"
myserver | SUCCESS => {
    "ansible_lsb.description": "Ubuntu 12.04.4 LTS",
    "changed": false
}
于 2016-10-21T17:50:52.607 に答える