以下是ansible api简单的示例:
vim aa.py
- #!/usr/bin/env python
- # encoding: utf-8
- import json
- aa={
- "AA" : {
- "hosts" : ['192.168.0.41']
- }
- }
- print json.dumps(aa)
aa.py是一个Dynamic Inventory脚本,当然,也可以不用这个脚本,直接用ansible默认的hosts就行 关于Dynamic Inventory可以参考:http://www.linuxyw.com/388.html 以下是ansible python api脚本 vim bb.py
- #!/usr/bin/env python
- # encoding: utf-8
- import ansible.runner
- aa = ansible.runner.Runner(
- module_name = 'shell', #调用shell模块,这个代码是为了示例执行shell命令
- module_args = 'hostname', #shell命令
- host_list = 'aa.py', #host文件路径,我这调用的是dynamic inventory脚本,
- pattern = 'AA', #host组名,需要执行shell命令的ip组,AA是在上面aa.py中定义的
- ) #其它没写的参数,都为是系统默认的
- bb = aa.run()
- print bb
脚本执行结果:
{'dark': {}, 'contacted': {u'192.168.0.41': {u'cmd': u'hostname', u'end': u'2014-10-20 10:17:55.703254', u'stdout': u'drfdai2', u'changed': True, u'start': u'2014-10-20 10:17:55.697105', u'delta': u'0:00:00.006149', u'stderr': u'', u'rc': 0, 'invocation': {'module_name': 'shell', 'module_args': 'hostname'}}}}
返回的stdout对应的value就是我们要的shell结果
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏