Python API 2.0
从2.0的事情开始更复杂一些,但是你会得到更多离散和可读的类:
#!/usr/bin/env python
import json
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback import CallbackBase
class ResultCallback(CallbackBase):
"""用于执行结果的示例回调插件
如果要将所有结果收集到单个对象进行处理
执行的结束,看看利用``json``回调插件
或编写自己的自定义回调插件
"""
def v2_runner_on_ok(self, result, **kwargs):
"""打印结果的json表示
该方法可以将结果存储在实例属性中以供以后检索
"""
host = result._host
print json.dumps({host.name: result._result}, indent=4)
Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check'])
# initialize needed objects
variable_manager = VariableManager()
loader = DataLoader()
options = Options(connection='local', module_path='/path/to/mymodules', forks=100, become=None, become_method=None, become_user=None, check=False)
passwords = dict(vault_pass='secret')
#实例化我们的ResultCallback来处理结果进来时
results_callback = ResultCallback()
#创建库存并传递给var manager
inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list='localhost')
variable_manager.set_inventory(inventory)
# create play with tasks
play_source = dict(
name = "Ansible Play",
hosts = 'localhost',
gather_facts = 'no',
tasks = [
dict(action=dict(module='shell', args='ls'), register='shell_out'),
dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
]
)
play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
# actually run it
tqm = None
try:
tqm = TaskQueueManager(
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
options=options,
passwords=passwords,
stdout_callback=results_callback, # Use our custom callback instead of the ``default`` callback plugin
)
result = tqm.run(play)
finally:
if tqm is not None:
tqm.cleanup()
Python API pre 2.0
这很简单:
import ansible.runner
runner = ansible.runner.Runner(
module_name='ping',
module_args='',
pattern='web*',
forks=10
)
datastructure = runner.run()
运行方法返回每个主机的结果,根据是否可以联系来分组。 返回类型是模块特定的,如关于模块文档中所示:
{
"dark" : {
"web1.example.com" : "failure message"
},
"contacted" : {
"web2.example.com" : 1
}
}
一个模块可以返回任何类型的JSON数据,所以Ansible可以作为框架来快速构建强大的应用程序和脚本。
详细API示例
以下脚本打印出所有主机的正常运行时间信息:
#!/usr/bin/python
import ansible.runner
import sys
# construct the ansible runner and execute on all hosts
results = ansible.runner.Runner(
pattern='*', 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本身,因为它使用API(具有所有可用选项)来实现可执行的命令行工具(lib / ansible / cli /)。
更多信息请参考官网:http://docs.ansible.com/ansible/latest/dev_guide/developing_api.html
及时行乐