python之ansible 2.0 API,pythonansible


ansible 2.0之后没有了run这个api,在网上找了很多官员2.0的API,发现调用的时候,返回结果居然只是0和1,无法获取想running一样的结果,经过研究,终于用下面的代码可以获取结果了,这个是我封装好的API。直接看代码

ansible_api.py

# coding=utf-80
#!/bin/env python

"""
@version: 1.0
@author: hogan
@project: CloudManage
@file: ansible_api.py
@time: 2016/7/5 11:16
"""

import os
import sys
import json
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.executor.playbook_executor import PlaybookExecutor
from ansible.playbook.play import Play
from ansible import constants as C
from ansible.plugins.callback import CallbackBase
from ansible.executor.task_queue_manager import TaskQueueManager


def Playbook_Run(host, playbook_path):
    variable_manager = VariableManager()
    loader = DataLoader()
    inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=host)
    Options = namedtuple('Options', ['listtags', 'listtasks', 'listhosts', 'syntax', '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'])    options = Options(listtags=False, listtasks=False, listhosts=False, syntax=False, connection='ssh', module_path=None, forks=100, remote_user='root', private_key_file=None, ssh_common_args
=None, ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None, become=True, become_method=None, become_user='root', verbosity=None, check=False)    passwords = {}
    pbex = PlaybookExecutor(playbooks=[playbook_path], inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=passwords)
    result =  pbex.run()
    return result


def Order_Run(host, module_name, module_args):
    class ResultCallback(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
                

    variable_manager = VariableManager()
    loader = DataLoader()
    inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=host)
    Options = namedtuple('Options', ['listtags', 'listtasks', 'listhosts', 'syntax', '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'])    options = Options(listtags=False, listtasks=False, listhosts=False, syntax=False, connection='ssh', module_path=None, forks=100, remote_user='root', private_key_file=None, ssh_common_args
=None, ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None, become=True, become_method=None, become_user='root', verbosity=None, check=False)    passwords = {}
    
    play_source = dict(
                    name="Ansible Play",
                    hosts=host,
                    gather_facts='no',
                    tasks=[dict(action=dict(module=module_name, args=module_args))]
                    )
    play = Play().load(play_source, variable_manager=variable_manager, loader=loader)

    tqm = None
    callback = ResultCallback()
    try:
        tqm = TaskQueueManager(
                inventory=inventory,
                variable_manager=variable_manager,
                loader=loader,
                options=options,
                passwords=passwords,
                stdout_callback=callback,
                run_additional_callbacks=C.DEFAULT_LOAD_CALLBACK_PLUGINS,
                run_tree=False,
                )
        
        result = tqm.run(play)
    finally:
        if tqm is not None:
            tqm.cleanup()
    results_raw = {}
    results_raw['success'] = {}
    results_raw['failed'] = {}
    results_raw['unreachable'] = {}

    for host, result in callback.host_ok.items(): 
        results_raw['success'][host] = json.dumps(result._result)  
  
    for host, result in callback.host_failed.items():
        results_raw['failed'][host] = result._result['msg']  
  
    for host, result in callback.host_unreachable.items():
        results_raw['unreachable'][host]= result._result['msg']  
    return results_raw

其中在另外一个test_api.py文件中调用了以上的接口

# coding=utf-8
#!/bin/env python

from ansible_api import Order_Run, Playbook_Run


print Order_Run(host=['192.168.180.150', '192.168.180.149'], module_name='shell', module_args='ls /root')
print Playbook_Run(host=['192.168.180.150', '192.168.180.149'], playbook_path='/etc/ansible/main.yml')


其中playbook中引用的pb /etc/anisble/main.yml为:

---
- hosts: all
  remote_user: root
  tasks:
    - name: Test ansible api
      shell: ls

然后运行test_api.py得到以下结果:


红色部分是调用Order_Run返回的结果。

相关内容

    暂无相关文章