Ansible-playbook API 2.0

Source: Internet
Author: User
Tags dataloader

Official documents See http://docs.ansible.com/ansible/dev_guide/developing_api.html

Take the official example and revise it as follows

ImportJSON fromCollectionsImportNamedtuple fromAnsible.parsing.dataloaderImportDataloader fromAnsible.varsImportVariablemanager fromAnsible.inventoryImportInventory fromAnsible.playbook.playImportPlay fromAnsible.executor.task_queue_managerImportTaskqueuemanager
From Ansible.executor.task_result import Taskresult fromAnsible.plugins.callbackImportCallbackbase#Custom callback, which calls V2_RUNNER_ON_OK () in this class after running the API, will output the host and result formats hereclassResultcallback (callbackbase):"""A sample callback plugin used for performing an action as results come on If you want to collect all results into A Single object for processing in the end of the execution, look into utilizing the ' JSON ' callback plugin or Writi Ng your own custom callback plugin""" defV2_RUNNER_ON_OK (self, result, * *Kwargs):"""Print A JSON representation of the result this method could store the result under an instance attribute for Retri Eval later""" #result contains ' _check_key ', ' _host ', ' _result ', ' _task ', ' is_changed ', ' is_failed ', ' is_skipped ', ' is_unreachable 'Host =Result._hostPrintJson.dumps ({Host.name:result._result}, indent=4) """def v2_on_any (self, *args, **kwargs): If Isinstance (Args[0], Taskresult): Print json.dumps ({args [0]._host.name:args[0]._result}, Indent=4)"""Options= Namedtuple ('Options', ['Connection','Module_path','Forks','become','Become_method','Become_user','Check'])#Initialize needed objectsVariable_manager =Variablemanager () loader=Dataloader () options= Options (connection='Smart', Module_path=none, forks=100, Become=none, Become_method=none, Become_user=none, check=False) Passwords= Dict (conn_pass='MyPassword')#currently only two key,conn_pass are found, Become_pass#instantiate our resultcallback for handling results as they come inResults_callback =Resultcallback ()#create inventory and pass to Var managerInventory = Inventory (Loader=loader, Variable_manager=variable_manager, host_list='hosts')#Hosts file, or it can be an IP listvariable_manager.set_inventory (Inventory)#Create play with TasksPlay_source =dict (Name="Ansible Play", the hosts='Web',#the hosts variable that corresponds to the Playbook entry Yaml file, or it can be an IPGather_facts ='No', Tasks=[Dict (Action=dict (module='Shell', args='ifconfig'), 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#Taskqueuemanager is the creation of a process pool that is responsible for the output and multi-process data structures or shared collaboration of the queuesTQM =NoneTry: TQM=Taskqueuemanager (Inventory=Inventory, Variable_manager=Variable_manager, Loader=Loader, Options=Options, Passwords=passwords, Stdout_callback=results_callback,#Use our custom callback instead of the ' default ' callback plugin #If the comment is dropped, the native default_stdout_callback is called, output of task result is callback, with Ansible-playbook debug) Result=Tqm.run (play)PrintResult#return code, as long as there is a host error will return a non-0 numberfinally: ifTqm is notNone:tqm.cleanup ()

If you need a unified output you can override

V2_runner_on_failed (self, result, ignore_errors=False) V2_runner_on_ok (self, result) v2_runner_on_skipped (self, Result) v2_runner_on_unreachable (self, result) v2_runner_on_no_hosts (self, Task)
Refer to plugins/callback/__init__.py for details

Ansible-playbook API 2.0

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.