栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

ansible pythonAPI编写

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/977940.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号