Ansible 2.6 Pthon API

核心代码

python3.6

ansible 2.6

ansibleAPI 常用模块

用于读取yaml,json格式的文件
from ansible.parsing.dataloader import DataLoader
#用于管理变量的类,包括主机,组,扩展等变量
from ansible.vars.manager import VariableManager
#用于创建和管理inventory,倒入inventory文件
from ansible.inventory.manager import InventoryManager
#ad-hoc 存储着角色列表,任务,处理代码块
from ansible.playbook.play import Play
#ad-hoc ansible底层用到的任务队列
from ansible.executor.task_queue_manager import TaskQueueManager
#回调基类,用来定义回调事件,比如返回失败成功等信息
from ansible.plugins.callback import CallbackBase
#执行playbook
from ansible.executor.playbook_executor import PlaybookExecutor
#操作单个主机
from ansible.inventory import host
#操作单个主机组
from ansible.inventory import group



InventoryManager

#实例化需要两个参数
"参数一为读取yml文件的信息,需要实例化 DataLoader"
"参数二为读取从那个位置读取资产配置文件,多个可逗号分割"
intertory = InventoryManager(loader='',sources='')
#以字典的方式打印出主机和主机组相关信息
intertory.get_group_dict()
#获取所有的主机
inventory.get_hosts()
#添加主机到指定主机组
"参数一指定主机地址"
"参数二指定主机端口"
"参数三指定主机群组,必须存在的群组"
inventory.add_host(host='10.1.41.200',port=2222,group='game_group')
#获取指定的主机对象
inventory.get_host(hostname='10.1.41.200')


VariableManager

#实例化需要两个参数
"参数一为读取yml文件的信息,需要实例化 DataLoader"
"参数二为资产管理配置变量"
variable = VariableManager(loader=loader,inventory=inventory)
#获取变量
variable.get_vars()
# 查看指定主机的详细变量信息
"传入的host是inventory.get_host获得的主机对象"
host = inventory.get_host(hostname='10.1.41.200')
host_vars = variable.get_vars(host=host)
#设置主机变量方法 
"传入的host是inventory.get_host获得的主机对象"
host = inventory.get_host(hostname='10.1.41.200')
variable.set_host_variable(host=host,varname='ansible_ssh_pass',value='root')
variable.set_host_variable(host=host,varname='ansible_ssh_user',value='root')
#添加扩展变量
"参数是一个字典多个逗号分割"
variable.extra_vars={'devops':'best'}

#!/usr/bin/env python

from collections import namedtuple

from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.inventory.manager import InventoryManager
from ansible.parsing.dataloader import DataLoader
from ansible.playbook.play import Play
from ansible.plugins.callback import CallbackBase
from ansible.vars.manager import VariableManager


# Create a callback object so we can capture the output
class ResultsCollector(CallbackBase):

    def __init__(self, *args, **kwargs):
        super(ResultsCollector, self).__init__(*args, **kwargs)
        self.host_ok = {}
        self.host_unreachable = {}
        self.host_failed = {}

    def v2_runner_on_unreachable(self, result):
        self.host_unreachable[result._host.get_name()] = result

    def v2_runner_on_ok(self, result, *args, **kwargs):
        self.host_ok[result._host.get_name()] = result

    def v2_runner_on_failed(self, result, *args, **kwargs):
        self.host_failed[result._host.get_name()] = result


def main():
    host_list = ['10.1.41.210','10.1.41.200']
    Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'remote_user',
                                     'private_key_file', 'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args',
                                     'scp_extra_args', 'become', 'become_method', 'become_user', 'verbosity', 'check',
                                     'diff'])
    # required for
    # https://github.com/ansible/ansible/blob/devel/lib/ansible/inventory/manager.py#L204
    sources = ','.join(host_list)
    if len(host_list) == 1:
        sources += ','

    # initialize needed objects
    loader = DataLoader()
    options = Options(connection='smart', module_path=['/usr/share/ansible'], forks=100,
                      remote_user=None, private_key_file=None, ssh_common_args=None, ssh_extra_args=None,
                      sftp_extra_args=None, scp_extra_args=None, become=None, become_method=None,
                      become_user=None, verbosity=None, check=False, diff=False,)

    passwords = dict()

    # create inventory and pass to var manager
    inventory = InventoryManager(loader=loader, sources=sources)
    variable_manager = VariableManager(loader=loader, inventory=inventory)
    for host in host_list:
        inventory.add_host(host=host,port=65534)
        hostname=inventory.get_host(hostname=host)
        variable_manager.set_host_variable(host=hostname,varname='ansible_ssh_pass',value='root')
        variable_manager.set_host_variable(host=hostname,varname='ansible_ssh_user',value='root')

    # create play with tasks
    play_source = dict(
        name="Ansible Play",
        hosts=host_list,
        gather_facts='no',
        #tasks=[dict(action=dict(module='command', args=dict(cmd='/usr/bin/uptime')))]
        #tasks=[dict(action=dict(module='shell', args='/usr/sbin/ip a'))]
        tasks=[
                dict(action=dict(module='setup', args='')),
        #        dict(action=dict(module='setup', args=''),register='shell_out'),
        #        dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
        ]
    )
    play = Play().load(play_source, variable_manager=variable_manager, loader=loader)

    # actually run it
    tqm = None
    callback = ResultsCollector()
    try:
        tqm = TaskQueueManager(
            inventory=inventory,
            variable_manager=variable_manager,
            loader=loader,
            options=options,
            passwords=passwords,
        )
        tqm._stdout_callback = callback
        result = tqm.run(play)
    finally:
        if tqm is not None:
            tqm.cleanup()

    print("UP ***********")
    for host, result in callback.host_ok.items():
        try:
            print('{0} >>> {1}'.format(host, result._result['stdout']))
        except :
            print('{0} >>> {1}'.format(host, result._result['ansible_facts']))

    print("FAILED *******")
    for host, result in callback.host_failed.items():
        print('{0} >>> {1}'.format(host, result._result['msg']))

    print("DOWN *********")
    for host, result in callback.host_unreachable.items():
        print('{0} >>> {1}'.format(host, result._result['msg']))


if __name__ == '__main__':
    main()

基于上面的内容,自己封装的API 如下:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author : liuyu
# date : 2018/8/6 0006


from collections import namedtuple

from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.inventory.manager import InventoryManager
from ansible.parsing.dataloader import DataLoader
from ansible.playbook.play import Play
from ansible.plugins.callback import CallbackBase
from ansible.vars.manager import VariableManager
import ansible.constants as C

C.HOST_KEY_CHECKING = False


def default_taskinfos():
    TaskInfos = {
        "hostinfo": [
            {
                "host": "0.0.0.0",
                "port": 22,
                "user": "root",
                "password": "root"
            },
        ],
        "taskinfo": [
            {
                "module": "setup",
                "args": ""
            },
        ]
    }
    return TaskInfos


# Create a callback object so we can capture the output
class ResultsCollector(CallbackBase):

    def __init__(self, *args, **kwargs):
        super(ResultsCollector, self).__init__(*args, **kwargs)
        self.host_ok = {}
        self.host_unreachable = {}
        self.host_failed = {}

    def v2_runner_on_unreachable(self, result):
        self.host_unreachable[result._host.get_name()] = result

    def v2_runner_on_ok(self, result, *args, **kwargs):
        self.host_ok[result._host.get_name()] = result

    def v2_runner_on_failed(self, result, *args, **kwargs):
        self.host_failed[result._host.get_name()] = result


class AnsibleApi(object):

    def __init__(self, TaskInfos):
        self.taskinfo = TaskInfos.get('taskinfo', default_taskinfos()["taskinfo"])
        self.hostinfo = TaskInfos.get('hostinfo', default_taskinfos()["hostinfo"])
        self.resultinfo = []

    def run(self):
        host_list = []
        [host_list.append(i.get("host", '0.0.0.0')) for i in self.hostinfo]
        Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'remote_user',
                                         'private_key_file', 'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args',
                                         'scp_extra_args', 'become', 'become_method', 'become_user', 'verbosity',
                                         'check',
                                         'diff'])
        # required for
        # https://github.com/ansible/ansible/blob/devel/lib/ansible/inventory/manager.py#L204
        sources = ','.join(host_list)
        if len(host_list) == 1:
            sources += ','

        # initialize needed objects
        loader = DataLoader()
        options = Options(connection='smart', module_path=['/usr/share/ansible'], forks=100,
                          remote_user=None, private_key_file=None, ssh_common_args=None, ssh_extra_args=None,
                          sftp_extra_args=None, scp_extra_args=None, become=None, become_method=None,
                          become_user=None, verbosity=None, check=False, diff=False, )

        passwords = dict(sshpass=None, becomepass=None)

        # create inventory and pass to var manager
        inventory = InventoryManager(loader=loader, sources=sources)
        variable_manager = VariableManager(loader=loader, inventory=inventory)
        for host in self.hostinfo:
            inventory.add_host(host=host.get('host'), port=host.get('port'))
            hostname = inventory.get_host(hostname=host.get('host'))
            variable_manager.set_host_variable(host=hostname, varname='ansible_ssh_pass', value=host.get('password'))
            variable_manager.set_host_variable(host=hostname, varname='ansible_ssh_user', value=host.get('user'))
            variable_manager.set_host_variable(host=hostname, varname='ansible_ssh_port', value=host.get('port'))
            # print("设置全局管理变量 %s"%host.get('host'))
        # create play with tasks
        tasks = []
        # print(self.taskinfo)
        for task in self.taskinfo:
            # tasks.append(dict(action=dict(module=task.get("module"), args=task.get("args"))))
            play_source = dict(
                name="Ansible API Play",
                hosts=host_list,
                gather_facts='no',
                # tasks=[dict(action=dict(module='command', args=dict(cmd='/usr/bin/uptime')))]
                # tasks=[dict(action=dict(module='shell', args='/usr/sbin/ip a'))]
                tasks=[dict(action=dict(module=task.get("module"), args=task.get("args")))]
                # dict(action=dict(module='setup', args='')),
                #        dict(action=dict(module='setup', args=''),register='shell_out'),
                #        dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))

            )
            play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
            # actually run it
            tqm = None
            callback = ResultsCollector()
            try:
                tqm = TaskQueueManager(
                    inventory=inventory,
                    variable_manager=variable_manager,
                    loader=loader,
                    options=options,
                    passwords=passwords,
                )
                tqm._stdout_callback = callback
                result = tqm.run(play)
            finally:
                if tqm is not None:
                    tqm.cleanup()

            # print("UP ***********")
            # print(callback.host_ok.items())
            for host, result in callback.host_ok.items():
                try:
                    # print('{0} >>> {1}'.format(host, result._result['stdout']))
                    self.resultinfo.append({host: {"message":result._result['stdout'],"code":0}})
                except:
                    # print('{0} >>> {1}'.format(host, result._result['ansible_facts']))
                    self.resultinfo.append({host: {"message":result._result['ansible_facts'],"code":0}})

            # print("FAILED *******")
            for host, result in callback.host_failed.items():
                # print('{0} >>> {1}'.format(host, result._result['msg']))
                self.resultinfo.append({host: {"message":result._result['msg'],"code":1}})

            # print("DOWN *********")
            for host, result in callback.host_unreachable.items():
                # print('{0} >>> {1}'.format(host, result._result['msg']))
                self.resultinfo.append({host: {"message":result._result['msg'],"code":-1}})

        return self.resultinfo


def Baserun(TaskInfos):
    TaskInfos = {
        "hostinfo": [
            {
                "host": "10.1.41.210",
                "port": 65534,
                "user": "root",
                "password": "root"
            },
            {
                "host": "10.1.41.220",
                "port": 6553,
                "user": "root",
                "password": "root"
            },
        ],
        "taskinfo": [
            {
                "module": "shell",
                "args": "hostname"
            },
            {
                "module": "command",
                "args": "/usr/bin/uptime"
            },
        ]
    }
    ansibleapi = AnsibleApi(TaskInfos)
    results = ansibleapi.run()
    print(results)


def getsysinfo(hostinfo):
    TaskInfos = {
        "hostinfo": [
            {
                "host": "10.1.41.210",
                "port": 65534,
                "user": "root",
                "password": "root"
            },
            {
                "host": "10.1.41.220",
                "port": 6553,
                "user": "root",
                "password": "root"
            },
        ],
        "taskinfo": [
            {
                "module": "setup",
                "args": ""
            },
        ]
    }
    TaskInfos["hostinfo"]=hostinfo
    # print(TaskInfos)
    ansibleapi = AnsibleApi(TaskInfos)
    result = ansibleapi.run()
    resultinfo=[]
    # print(result)
    for res in result:
        for k in res:
            data = res[k]["message"]
            code=res[k]["code"]

            sysinfo = {}
            disksize=0
            if code !=0:
                resultinfo.append({k: res[k]})
            else:
                for i in data["ansible_devices"]:
                    if i[0:2] in ("vd", "ss", "sd"):
                        disksize=disksize+int(data["ansible_devices"][i]["sectors"]) * int(
                            data["ansible_devices"][i]["sectorsize"]) / 1024 / 1024 / 1024
                sysinfo['disk'] = "{}".format(str(disksize) + str(" GB"))
                sysinfo['mem'] = round(data['ansible_memtotal_mb'] / 1024)
                sysinfo['cpu'] = "{} * {}".format(data['ansible_processor_count'] * data["ansible_processor_cores"],
                                                  data['ansible_processor'][2])
                sysinfo['system'] = data['ansible_distribution'] + " " + data['ansible_distribution_version']
                resultinfo.append({k:{"message":sysinfo,"code":0}})
    return resultinfo




def execshell(hostinfo, shellcmd):
    TaskInfos = {
        "hostinfo": [
            {
                "host": "10.1.41.210",
                "port": 65534,
                "user": "root",
                "password": "root"
            },
            {
                "host": "10.1.41.220",
                "port": 6553,
                "user": "root",
                "password": "root"
            },
        ],
        "taskinfo": [
            {
                "module": "shell",
                "args": ""
            },
        ]
    }
    TaskInfos["hostinfo"]=hostinfo
    TaskInfos["taskinfo"][0]["args"] = shellcmd
    ansibleapi = AnsibleApi(TaskInfos)
    result = ansibleapi.run()
    return result

# data=getsysinfo([{"host": "10.1.41.220","port": 6553,"user": "root","password": "root"}])
# print(data)
# [{'10.1.41.220': {'disk': '30.0 GB', 'mem': 2, 'cpu': '4 * Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz', 'system': 'CentOS 7.2.1511'}}]

# data=execshell([{"host": "10.1.41.220","port": 6553,"user": "root","password": "root"}], "uptime")
# print(data)
# [{'10.1.41.220': ' 01:14:30 up  2:24,  2 users,  load average: 0.01, 0.02, 0.05'}]

  • Ansible 2.6 Pthon API已关闭评论
  • 1,780 views
    A+
发布日期:2018年08月06日  所属分类:Python