ansible 提供了python api可以供python程序直接调用,下面看一下具体例子
#!/usr/bin/env python
import json
import shutil
from ansible.module_utils.common.collections import ImmutableDict
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback import CallbackBase
from ansible import context
import ansible.constants as C
class ResultCallback(CallbackBase):
"""A sample callback plugin used for performing an action as results come in
If you want to collect all results into a single object for processing at
the end of the execution, look into utilizing the ``json`` callback plugin
or writing your own custom callback plugin
"""
def v2_runner_on_ok(self, result, **kwargs):
"""Print a json representation of the result
This method could store the result in an instance attribute for retrieval later
"""
host = result._host
print(json.dumps({host.name: result._result}, indent=4))
# since the API is constructed for CLI it expects certain options to always be set in the context object
context.CLIARGS = ImmutableDict(connection='ssh', module_path=['/to/mymodules'], forks=10, become=None,
become_method=None, become_user=None, check=False, diff=False)
# initialize needed objects
loader = DataLoader() # Takes care of finding and reading yaml, json and ini files
passwords = dict(vault_pass='secret')
# Instantiate our ResultCallback for handling results as they come in. Ansible expects this to be one of its main display outlets
results_callback = ResultCallback()
# create inventory, use path to host config file as source or hosts in a comma separated string
inventory = InventoryManager(loader=loader, sources='192.168.1.2,192.168.1.3,')
# variable manager takes care of merging all the different sources to give you a unified view of variables available in each context
variable_manager = VariableManager(loader=loader, inventory=inventory)
variable_manager.extra_vars = {'ansible_ssh_user': 'test', 'ansible_ssh_pass': 'test', 'StrictHostKeyChecking': 'no'}
# create data structure that represents our play, including tasks, this is basically what our YAML loader does internally.
play_source = dict(
name = "Ansible Play",
hosts = 'all',
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}}')))
]
)
# Create play object, playbook objects use .load instead of init or new methods,
# this will also automatically create the task objects from the info provided in play_source
play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
# Run it - instantiate task queue manager, which takes care of forking and setting up all objects to iterate over host list and tasks
tqm = None
try:
tqm = TaskQueueManager(
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
passwords=passwords,
stdout_callback=results_callback, # Use our custom callback instead of the ``default`` callback plugin, which prints to stdout
)
result = tqm.run(play) # most interesting data for a play is actually sent to the callback's methods
finally:
# we always need to cleanup child procs and the structures we use to communicate with them
if tqm is not None:
tqm.cleanup()
# Remove ansible tmpdir
shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
context.CLIARGS 相当于设置ansible.cfg设置一些ansible基础运行环境 loader 用于解析yaml和json等文件 results_callback 用于每个任务执行结果加调处理,可以自定义,继承CallbackBase即可,可供回调处理的节点还是挺丰富的.包括v2_runner_on_failed,v2_runner_on_ok,v2_runner_on_skipped,具体可以看CallbackBase里面定义的函数接口 inventory 类似手动执行的hosts文件,sources参数一个用逗号分隔的字符串,注意结尾要一个逗号,这跟host_list_args这个Plugin插件实现有关 variable_manager 是我们在hosts文件定义的一些参数,可以根据自己需求添加 play_source 就是具体定义的playbook,格式就是把Playbook转换成python数据格式,还是比较简单的,里面tasks的task可以根据自己需求,跟playbook定义差不多,一个复杂task定义
dict(name='copy', action=dict(module='copy', args=dict(src='a.txt', dest='b.txt', owner='roow', mode=0644)), become='root', tags=['test'])
play 作为ansible脚本类似于playbook的对象
TaskQueueManager 是ansible执行引擎