标签:
因项目需要使用到ansible api,按照改削官方文档供给的使用典型,颠末多次测试,现将能用的代码分享给大家,大家只需按照本身的实际环境改削该代码即可。
官方文档:
#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()
我的../conf/hosts文件内容如下:
[cephnode]
192.168.89.136
注意:
如没有明确指定inventory(如下的参数),那么会默认从/etc/ansible/hosts中读取hosts
sources=['../conf/hosts']
增补一下,刚说了界说多条任务的方法,举个例子:
tasks = [
dict(action=dict(module='shell', args='mkdir /tmp/toby'), register='shell_out'), #首先创建目录
dict(action=dict(module='copy', args='src=http://www.mamicode.com/tmp/abc123.txt dest=http://www.mamicode.com/tmp/toby'), register='shell_out') #然后将本地的abc123.txt通过copy模块下发到方针主机的/tmp/toby/目录下
]
Ansible API 2.0的测试