如何使用Ansible 2的API做python开发

如题所述

import ansible.runner
runner = ansible.runner.Runner(
module_name='ping',
module_args='',
pattern='web*',
forks=10
)
datastructure = runner.run()
ansible.executor.task_queue_manager

这是ansible的一个内部模块(ansible/executor/task_queue_manager.py)。初始化的源码如下:
class TaskQueueManager:
'''
This class handles the multiprocessing requirements of Ansible by
creating a pool of worker forks, a result handler fork, and a
manager object with shared datastructures/queues for coordinating
work between all processes.
The queue manager is responsible for loading the play strategy plugin,
which dispatches the Play's tasks to hosts.
'''
def __init__(self, inventory, variable_manager, loader, options, passwords, stdout_callback=None, run_additional_callbacks=True, run_tree=False):self._inventory = inventoryself._variable_manager = variable_managerself._loader = loaderself._options = optionsself._stats = AggregateStats()self.passwords = passwordsself._stdout_callback = stdout_callbackself._run_additional_callbacks = run_additional_callbacksself._run_tree = run_treeself._callbacks_loaded = Falseself._callback_plugins = []self._start_at_done = Falseself._result_prc = None……
创建时,需要的主要参数包括:
inventory --> 由ansible.inventory模块创建,用于导入inventory文件
variable_manager --> 由ansible.vars模块创建,用于存储各类变量信息
loader --> 由ansible.parsing.dataloader模块创建,用于数据解析
options --> 存放各类配置信息的数据字典
passwords --> 登录密码,可设置加密信息
stdout_callback --> 回调函数
ansible.playbook.play

ansible.playbook是一个原生模块,既用于CLI也用于API。从源码可以看出来:
try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
display = Display()

ansible.playbook.play(ansible/playbook/play.py)。初始化源码的介绍如下:

__all__ = ['Play']

class Play(Base, Taggable, Become):
"""
A play is a language feature that represents a list of roles and/or
task/handler blocks to execute on a given set of hosts.
Usage:
Play.load(datastructure) -> Play
Play.something(...)
"""
最后,用task_queue_manager(play)来执行,老规矩,源码的官方解释。
def run(self, play):'''Iterates over the roles/tasks in a play, using the given (or default)strategy for queueing tasks. The default is the linear strategy, whichoperates like classic Ansible by keeping all hosts in lock-step witha given task (meaning no hosts move on to the next task until all hostsare done with the current task).'''
温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

大家正在搜

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网