Ansible API 2.0的测试
2021-02-19 17:18
标签:.exe source pac for cep develop usr href dev 官方文档:http://docs.ansible.com/ansible/latest/dev_guide/developing_api.html#python-api-2-0 我的../conf/hosts文件内容如下: [cephnode] 注意: 如没有明确指定inventory(如下的参数),那么会默认从/etc/ansible/hosts中读取hosts 补充一下,刚说了定义多条任务的方式,举个例子: Ansible API 2.0的测试 标签:.exe source pac for cep develop usr href dev 原文地址:http://blog.51cto.com/freshair/2062406#coding:utf-8
import json
from collections import namedtuple
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
class ResultCallback(CallbackBase):
def v2_runner_on_ok(self, result, **kwargs):
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', 'diff'])
# module_path参数指定本地ansible模块包的路径
loader = DataLoader()
options = Options(connection='smart', module_path='/usr/lib/python2.7/dist-packages/ansible/modules', forks=5, become=None, become_method=None, become_user="root", check=False, diff=False)
passwords = dict(vault_pass='secret')
# 实例化ResultCallback来处理结果
results_callback = ResultCallback()
# 创建库存(inventory)并传递给VariableManager
inventory = InventoryManager(loader=loader, sources=['../conf/hosts']) #../conf/hosts是定义hosts
variable_manager = VariableManager(loader=loader, inventory=inventory)
# 创建任务
play_source = dict(
name = "Ansible Play",
hosts = "cephnode",
gather_facts = 'no',
tasks = [
dict(action=dict(module='shell', args='touch /tmp/7.txt'), register='shell_out'), #定义一条任务,如有多条任务也应按照这样的方式定义
]
)
play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
# 开始执行
tqm = None
try:
tqm = TaskQueueManager(
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
options=options,
passwords=passwords,
stdout_callback=results_callback, # 使用自定义回调代替“default”回调插件(如不需要stdout_callback参数则按照默认的方式输出)
)
result = tqm.run(play)
finally:
if tqm is not None:
tqm.cleanup()
192.168.89.136sources=['../conf/hosts']
tasks = [
dict(action=dict(module='shell', args='mkdir /tmp/toby'), register='shell_out'), #首先创建目录
dict(action=dict(module='copy', args='src=/tmp/abc123.txt dest=/tmp/toby'), register='shell_out') #然后将本地的abc123.txt通过copy模块下发到目标主机的/tmp/toby/目录下
]
下一篇:WPF重写Button样式
文章标题:Ansible API 2.0的测试
文章链接:http://soscw.com/index.php/essay/57618.html