前言:根据ansible2.8官方提供的接口,做了以下调整,可以加参数
例如:请求的参数是:{"fork":"5","hosts":[{"group":"aa","ip":"192.168.100.3","port":"22","vars":{"ansible_ssh_user":"root","ansible_ssh_pass":"123456"}}],"modules":"shell","args_list":"df -h"}
#!/usr/bin/env python
#encoding=utf-8
import json
import shutil,requests
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
#重写callback
class ResultCallback(CallbackBase):
def call_message(self,ip,message):
#将执行结果通过接口返回给server服务器
url = 'http://192.168.100.2/ansible/showstatus/?ip=%s&message=%s' % (ip,message)
text = requests.get(url)
#执行的结果正常
def v2_runner_on_ok(self, result, **kwargs):
host = result._host
self.call_message(host.name,result._result['stdout'])
print(host.name,result._result['stdout'])
print json.dumps({"hostname":host.name,"result":result._result['stdout']}, indent=4)
#主机不可达
def v2_runner_on_unreachable(self, result):
host = result._host.get_name()
self.call_message(host,result._result['msg'])
print json.dumps({"hostname":host,"result":result._result['msg']}, indent=4)
#执行失败
def v2_runner_on_failed(self, result, ignore_errors=False):
host = result._host.get_name()
self.call_message(host,result._result['msg'])
print json.dumps({"hostname":host,"result":result._result['msg']}, indent=4)
def operate(hosts):
fork = hosts["fork"]
context.CLIARGS = ImmutableDict(connection='ssh', module_path='/path/to/mymodules', forks=fork, become=None,
become_method=None,
become_user=None, check=False, diff=False)
passwords = dict(vault_pass='www')
results_callback = ResultCallback()
loader = DataLoader()
inventory = InventoryManager(loader)
for host in hosts["hosts"]:
try:
if host["group"] not in inventory.get_groups_dict()["group"]:
inventory.add_group(host["group"])
inventory.add_host(host["ip"], group=host["group"], port=host["port"])
except:
inventory.add_group(host["group"])
inventory.add_host(host["ip"], group=host["group"], port=host["port"])
variable_manager = VariableManager(loader=loader, inventory=inventory)
groups = []
for host in hosts["hosts"]:
groups.append(host["group"])
ip = inventory.get_host(host["ip"])
for key in host["vars"]:
variable_manager.set_host_variable(ip, key, host["vars"][key])
play_source = dict(
name="Test",
hosts=groups,
gather_facts='no',
tasks=[
dict(action=dict(module=hosts["modules"], args=hosts["args_list"]),register='shell_out'),
#dict(action=dict(module='shell', args='ls'), 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,
passwords=passwords,
stdout_callback=results_callback,
)
result=tqm.run(play)
finally:
if tqm is not None:
tqm.cleanup()
shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
hosts = {
'fork':'5',
'hosts':[
{
'group':'aa',
'ip':'192.168.100.3',
'port':'22',
'vars':{
'ansible_ssh_user':'root',
'ansible_ssh_pass':'123456'
}
}],
'modules':'shell',
'args_list':'df -h'
}
operate(hosts)