Python's Ansible 2.0 Api__python

Source: Internet
Author: User
Tags dataloader

After Ansible 2.0, there was no run this API, On the internet to find a lot of officials 2.0 of the API, found that the call, the return result is only 0 and 1, can not get the same results as running, after research, finally use the following code can get results, this is my encapsulated API. Look at the code directly

ansible_api.py

# coding=utf-80 #!/bin/env python "" "@version: 1.0 @author: Hogan @project: Cloudmanage @file: ansible_api.py @time: 201 6/7/5 11:16 "" Import OS import sys import JSON from collections import namedtuple from Ansible.parsing.dataloader Impor T Dataloader from ansible.vars import Variablemanager to ansible.inventory import inventory from Ansible.executor.playb Ook_executor Import Playbookexecutor from ansible.playbook.play Import to ansible import constants as C from Ansibl E.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 (loa Der=loader, Variable_manager=variable_manager, host_list=host) options = namedtuple (' Options ', [' listtags ', ' Listtask S ', ' 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_ru
                

    Nner_on_failed (self, result, *args, **kwargs): Self.host_failed[result._host.get_name ()] = result Variable_manager = Variablemanager () loader = Dataloader () inventory = Inventory (Loader=loader, Varia Ble_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 = Optio NS (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=[dic T (action=dict (Module=module_name, Args=module_args))] Play = Play (). Load (Play_source, variable_m Anager=variable_manager, loader=loader) TQM = None callback = Resultcallback () TRY:TQM = Taskqueuema Nager (Inventory=inventory, Variable_manager=variable_manager, Loader=load
                Er, 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 isn't 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.item S (): results_raw[' failed '][host] = result._result[' msg '] for host, result in callback.host_unreachable.it EMS (): results_raw[' unreachable '][host]= result._result[' msg '] return Results_raw

Which calls the above interface in another test_api.py file

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


Where the pb/etc/anisble/main.yml referenced in playbook is:

---
-hosts:all
  remote_user:root
  tasks:
    -name:test ansible API
      Shell:ls

Then run test_api.py to get the following results:


The red section is the result of invoking the Order_run return.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.