一. ansible 資源inventory 動態,腳本規範說明需要實現--list ,--host 選項,並輸出json數據即可。
1. --list 輸出:
[root@master_101 ansible]# ./dy_host.py --list { "all": [ "192.168.8.101", "192.168.8.102" ], "web": { "hosts": [ "192.168.8.101" ], "vars": { "aa": 10 } }, "web2": { "hosts": [ "192.168.8.101", "192.168.8.102" ] } }
## 其中 hosts,vars 是關鍵字符,不能改變
2. --host 輸出:
[root@master_101 ansible]# ./dy_host.py --host 192.168.8.102 { "ansible_host": "192.168.8.102", "ansible_port": 22, "ansible_user": "sun", "ansible_password": "qweasd", "ansible_become": "true", "ansible_become_method": "su", "ansible_become_user": "root", "ansible_become_pass": "qweasd" }
3. _meta 關鍵字使用
如果inventory腳本返回的頂級元素爲”_meta”,它可能會返回所有主機的變量.如果這個元素中包含一個名爲”hostvars”的value,這個inventory腳本對每一臺主機使用調用時候,就不會調用 --host 選項對目標主機進行操作,而是使用hostvars 中目標主機的信息對目標主機進行操作。
[root@master_101 ansible]# ./dy_host.py --list { "_meta": { "hostvars": { "192.168.8.101": { "ansible_user": "root", "ansible_password": "qweasd" }, "192.168.8.102": { "ansible_user": "sun", "ansible_password": "qweasd", "ansible_become": "true", "ansible_become_method": "su", "ansible_become_user": "root", "ansible_become_pass": "qweasd" } } }, "all": [ "192.168.8.101", "192.168.8.102" ], "web": { "hosts": [ "192.168.8.101" ], "vars": { "aa": 10 } }, "web2": { "hosts": [ "192.168.8.101", "192.168.8.102" ] } }
4 腳本例子
[root@master_101 ansible]# cat dy_host.py
#!/usr/bin/env python3 #coding:utf8 import json import sys def group(): hosts = { '_meta' : { "hostvars": { '192.168.8.101':{'ansible_user':'root','ansible_password':'qweasd'}, '192.168.8.102':{'ansible_user':'sun','ansible_password': 'qweasd', 'ansible_become':'true', 'ansible_become_method':'su', 'ansible_become_user':'root', 'ansible_become_pass':'qweasd' } } }, 'all': ['192.168.8.101','192.168.8.102'], 'web':{"hosts": ['192.168.8.101'],'vars': {'aa':10},}, 'web2': {"hosts":['192.168.8.101','192.168.8.102']} } print(json.dumps(hosts,indent=4)) def host(ip): hosts = { "192.168.8.101": { "ansible_host":"192.168.8.101", "ansible_port":22, "ansible_user":"root", "ansible_pass":"qweasd" }, "192.168.8.102": { "ansible_host":"192.168.8.102", "ansible_port":22, "ansible_user":"sun", "ansible_password":"qweasd", 'ansible_become':'true', 'ansible_become_method':'su', 'ansible_become_user':'root', 'ansible_become_pass':'qweasd' } } j = json.dumps(hosts[ip],indent=4) print(j) def main(): if len(sys.argv) == 2 and (sys.argv[1] == '--list'): group() elif len(sys.argv) == 3 and (sys.argv[1] == '--host'): host(sys.argv[2]) else: print("Usage: %s --list or --host <hostname>" % sys.argv[0]) if __name__ == '__main__': main()