2016-10-21 72 views
0

我想過濾ad-hoc命令的JSON輸出 - 例如,抓住多個主機的「facts」長列表,並且只顯示一個可能有幾個級別深度的列表,例如ansible_lsb.description,這樣我就可以快速比較它們運行的​​軟件版本,檢查準確的時間或時區等等。Ansible ad-hoc命令過濾器通過鍵或屬性輸出JSON

這工作:

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 
} 

然而,隨着setup module docs狀態, 「只有過濾選項過濾器下面ansible_facts第一級子項」,所以失敗:

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

(儘管參考,你可以在其他地方使用點符號,如任務的when conditional

有沒有一種方法可以在outp之前過濾JSON密鑰ut顯示?

回答

1

標準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模塊剝離myfilter參數,然後用過濾簡單的結果降低實施,如果任務沒有失敗,myfilter設置。查找功能非常簡單,所以它不能與列表一起使用,只能與對象一起使用。

結果:

$ ansible myserver -m setup -a "myfilter=ansible_lsb.description" 
myserver | SUCCESS => { 
    "ansible_lsb.description": "Ubuntu 12.04.4 LTS", 
    "changed": false 
} 
+0

謝謝!效果很好。 –