# -*- coding: UTF-8 -*-
import json,shutil
from ansible import context
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.executor.playbook_executor import PlaybookExecutor
import ansible.constants as C
from . import models
C.HOST_KEY_CHECKING = False
class ResultCallback(CallbackBase):
def __init__(self):
self.theresult = {}
def v2_runner_on_ok(self, result, **kwargs):
host = result._host
# print(type(self.result))
self.theresult[host.name] = result._result
# self.result.append(1)
def v2_runner_on_failed(self, result, **kwargs):
host = result._host
self.theresult[host.name] = result._result
def v2_runner_on_unreachable(self, result, **kwargs):
host = result._host
self.theresult[host.name] = result._result
##
class AnsibleApi:
context.CLIARGS = ImmutableDict(
connection='smart', remote_user='root',
module_path=None, verbosity=5,
become=None, become_method=None, become_user=None,
# become=True, become_method='sudo', become_user='root',
check=False, diff=None,
)
def __init__(self):
# self.name = name
# self.host_list = host_list
# self.task_list = task_list
self.loader = DataLoader()
self.result_callback = ResultCallback()
# self.passwords = dict(vault_pass=passwords)
self.passwords = dict()
self.inventory = InventoryManager(loader=self.loader, sources=['/etc/ansible/inventory/hosts','/etc/ansible/hosts'])
self.variable_manager = VariableManager(loader=self.loader, inventory=self.inventory)
#从数据库中灵活添加host
def __call__(self, host):
hosts = models.Myhost.objects.all()
for host in hosts:
self.inventory.add_host(host = host['hostname'], port = 22, group = host['groupname'])
self.variable_manager.set_host_variable(host = host['hostname'],varname='ansible_ssh_user',value = host['username'])
self.variable_manager.set_host_variable(host = host['hostname'], varname='ansible_ssh_pass', value = host['password'])
hostdict = self.inventory.get_groups_dict()
#print(hostdict)
return hostdict
def run_adhoc(self,hosts, tasks,name = 'Chekconnection'):
play_source = dict(
name=name,
hosts=hosts,
gather_facts='no',
tasks=tasks
)
play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader)
tqm = None
try:
tqm = TaskQueueManager(
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
passwords=self.passwords,
stdout_callback=self.result_callback,
# Use our custom callback instead of the ``default`` callback plugin, which prints to stdout
run_additional_callbacks=C.DEFAULT_LOAD_CALLBACK_PLUGINS,
run_tree=False,
)
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 structres we use to communicate with them
if tqm is not None:
tqm.cleanup()
# Remove ansible tmpdir
shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
return self.result_callback
def run_playhook(self, playbook):
# self.variable_manager.extra_vars = {
# 'customer': 'test',
# 'disabled': 'yes'
# }
playbook = PlaybookExecutor(
playbooks=playbook,
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
passwords=self.passwords,
)
result = playbook.run()
return result
if __name__ == '__main__':
a = AnsibleApi()
host_list = ['192.168.237.132']
task_list = [
dict(action=dict(module='shell', args="ls -l /etc"))
]
a.run_adhoc(name="checkConnection", hosts=host_list, tasks=task_list)
a.run_playhook(playbook=["/data/filebeat/filebeats.yml"])
#直接更改hosts文件:
def edit_hosts(host):
with open('/etc/ansible/hosts','r' ,encoding= 'utf-8') as f:
contents = f.readlines()
with open('/etc/ansible/hosts','w' ,encoding= 'utf-8') as f:
for content in contents:
print(content)
f.write(content)
if content == '[Node]\n':
f.write('{0} ansible_ssh_user="{1}" ansible_ssh_pass="{2}"\n'.format(host['hostname'],host['username'],host['password']))
elif content == '[Netequip]\n':
f.write('{0} ansible_ssh_user="{1}" ansible_ssh_pass="{2}"\n'.format(host['hostname'],host['username'],host['password']))
ansible pythonAPI编写
于 2022-06-15 10:27:34 首次发布