ansible pythonAPI编写

# -*- 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']))

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值