Ansible API 的使用非常強大,也非常簡單,只不過把模塊需要使用的參數寫到了腳本中。當業務比較大比較復雜的時候, 單純的使用Ansible有時候不會很好的完成相關的運維工作, 這個時候就需要開發針對自己業務的一些模塊或者ansible插件來完成這些工作。 Ansible還提供了Python接口,可以使用Python開發更為自動化的運維管理系統。
Ansible API
案例1:簡單的API示例,為了增加可視性,可以將結果進行json美化輸出
[ansible@lyjl_ansible scripts]$ cat ansible_api.py #!/usr/bin/env python # coding=utf-8 import ansible.runner import json runner = ansible.runner.Runner( module_name='ping', # 模塊名稱 module_args='', # 模塊參數 pattern='35_db', # 主機組 forks=10 # 並發量 ) datastructure = runner.run() data = json.dumps(datastructure,indent=4) print data [ansible@lyjl_ansible scripts]$ python ansible_api.py { "dark": { "lyjl-db-23-10.62.121.185": { "msg": "FAILED: [Errno 111] Connection refused", "failed": true } }, "contacted": { "lyjl-db-80-10.62.121.53": { "invocation": { "module_name": "ping", "module_args": "" }, "changed": false, "ping": "pong" }, "lyjl-db-60-10.62.121.53": { "invocation": { "module_name": "ping", "module_args": "" }, "changed": false, "ping": "pong" }, "lyjl-db-10-10.62.121.203": { "invocation": { "module_name": "ping", "module_args": "" }, "changed": false, "ping": "pong" }, "lyjl-db-79-10.62.121.203": { "invocation": { "module_name": "ping", "module_args": "" }, "changed": false, "ping": "pong" } } }
注:如果主機不通或者失敗,結果將會輸出到 dark部分,否則結果輸出到 contacted部分
案例2:復雜點的API案例
[ansible@lyjl_ansible scripts]$ cat 2.py #!/usr/bin/python import ansible.runner import sys # construct the ansible runner and execute on all hosts results = ansible.runner.Runner( pattern='35_db', forks=10, module_name='command', module_args='/usr/bin/uptime', ).run() if results is None: print "No hosts found" sys.exit(1) print "UP ***********" for (hostname, result) in results['contacted'].items(): if not 'failed' in result: print "%s >>> %s" % (hostname, result['stdout']) print "FAILED *******" for (hostname, result) in results['contacted'].items(): if 'failed' in result: print "%s >>> %s" % (hostname, result['msg']) print "DOWN *********" for (hostname, result) in results['dark'].items(): print "%s >>> %s" % (hostname, result) # 結果: [ansible@lyjl_ansible scripts]$ python 2.py UP *********** lyjl-db-60-10.62.121.53 >>> 11:45:03 up 427 days, 22:24, 0 users, load average: 0.20, 0.15, 0.11 lyjl-db-79-10.62.121.203 >>> 11:45:03 up 708 days, 36 min, 1 user, load average: 1.61, 0.84, 0.52 lyjl-db-10-10.62.121.203 >>> 11:45:04 up 708 days, 36 min, 1 user, load average: 1.61, 0.84, 0.52 lyjl-db-80-10.62.121.53 >>> 11:45:03 up 427 days, 22:24, 0 users, load average: 0.18, 0.14, 0.11 FAILED ******* DOWN ********* lyjl-db-23-10.62.121.185 >>> {'msg': 'FAILED: [Errno 111] Connection refused', 'failed': True}
注:上面的示例中對主機的輸出結果進行了判斷,並且對結果的輸出進行了定制化,同時可以對比下API的結果和命令行執行的結果的差異
ansible_playbook API
待補充
API總結
API應用場景
1)前一次的執行結果作為后一次任務的參數輸入
2)對任務的執行結果進行定制化輸出或者存儲
3)方便二次開發及和其他程序之間的耦合調用