Recently wanted to use Python to invoke anbile to implement some functions, found that the Ansible API has been upgraded to 2.0, the use of more complex than before.
Here I refer to the Official document example, did some rectification, wrote a python call ansible function, the execution process output execution results. The function returns the result of the execution, making it easy to filter and store the required data:
# vim exec_ansible.pydef exec_ansible (module,args,host): import json from collections import namedtuple from ansible.parsing.dataloader import dataloader from ansible.vars import VariableManager from ansible.inventory import inventory from ansible.playbook.play import play from ansible.executor.task_queue_manager import TaskQueueManager from ansible.plugins.callback import CallbackBase class Resultcallback (callbackbase): def v2_runner_on_ok (Self, result, **kwargs): host = result._host &Nbsp; self.data = json.dumps ({host.name: result._result}, indent=4) Print (Self.data) options = namedtuple (' Options ', [' connection ', ' Module_path ', ' forks ', ' become ', ' become_method ' [, ' Become_user ', ' Check ']) # Initialize needed objects variable_manager = variablemanager () loader = dataloader () #module_path参数指定本地ansible模块包的路径 options = options (connection= ' smart ', module_path= '/usr/local/lib/ Python3.5/site-packages/ansible/modules/', forks=100, become=none, become_method=none, Become_user= ' root ', check=false) passwords = dict (vault_pass= ' secret ') # Instantiate our resultcallback for handling results as they come in Results_callback = resultcallback () # create inventory and pass to var manager #host_list指定本地ansible的hosts文件 inventory = inventory (loader=loader, variable_manager=variable_manager, host_list= '/etc/ansible/hosts ') variable_manager.set_inventory (Inventory) # create play with tasks play_source = dict ( name = "Ansible play", #hosts可以指定inventory中的一组主机, you can also specify a single host hosts = host, gather_facts = ' No ', #task执行列表, if you want to perform multiple tasks at once, You can add tasks to the list tasks = [ dict (Action=dict ( Module=module, args=args), register= ' shell_out '), ] ) play = play (). Load (Play_source, variable_manager=variable_manager, loader=loader) # actually run it tqm = none try: tqm = taskqueuemanager ( inventory=inventory, variable_manager=variable_manager, loader=loader, options= options, passwords=passwords, stdout_callback=results_callback, ) result = Tqm.run (play) finally: if tqm Is not none: tqm.cleanup &Nbsp; return json.loads (Results_callback.data)
Invocation Example:
My local ansible Hosts file is as follows:
# more/etc/ansible/hosts[testserver]192.168.52.128192.168.52.135
The call is as follows:
Call TestServer a group of hosts to execute the date command in bulk:
>>> from exec_ansible import exec_ansible >>> test1 = exec_ansible (module= ' shell ', args= ' date ', host = ' testserver ') { "192.168.52.135": { "Warnings": [], "stderr": "", "Delta": "0:00:00.003688", " _ansible_no_log ": false, " stdout ": " Sat Nov 5 18:54:17 cst 2016 ", " cmd ": " Date ", " _ansible_parsed ": true, "RC": 0, "Invocation": { "Module_args": { "Removes": null, "Executable": null, "creates": null, "ChDir": null, "Warn": true, "_raw_ Params ": " date ", "_uses_shell": true }, "module_name": "command"         }, "Start": "2016-11-05 18:54:17.563525", "changed": true, "End" : "2016-11-05 18:54:17.567213", "Stdout_lines": [ "sat nov 5 18:54:17 cst 2016 " ] }}{ "192.168.52.128": { "warnings": [], "stderr": "", "Delta": "0:00:00.003244", "_ansible_no_log": false, "stdout": "sat nov 5 21:48:38 cst 2016 ", " cmd ": " Date ", "_ansible_parsed": true, "RC": 0, "Invocation": { "Module_args": { "Removes": null, "Executable": null, "creates": null, "ChDir": null, "Warn": true, "_raw_params": "date", "_uses_shell": true }, "module_name": "command" }, "Start": "2016-11-05 21:48:38.252785", "changed": true, "End": " 2016-11-05 21:48:38.256029 ", " Stdout_lines ": [ "sat nov 5 21:48:38 cst 2016" ] }}
To specify a single execution command:
>>> test2 = exec_ansible (module= ' shell ', args= ' free -m ', host= ' 192.168.52.128 ') { "192.168.52.128": { "warnings": [], "Changed": true, "Invocation": { "Module_args": { "_raw_params": "Free -m", "Executable": null, "ChDir": null, "creates": null, "Removes": null, "_uses_shell": true, "Warn": true }, "Module_name": "command" }, "RC": 0, "Start": "2016-11-05 21:53:10.738545 ", " _ansible_parsed ": true, "Delta": "0:00:00.002871", "Stdout_lines": [ " total used free shared buffers cached ", " Mem: 1869 1786 83 3 312 512 " , "-/+ buffers/cache: 961 908 ", "swap: 4047 3 4044 " ], " stderr ": " ", " End ": " 2016-11-05 21:53:10.741416 " , "cmd": "Free -m", "_ansible_no_log": false, "stdout": " total used free shared buffers cached\nMem: 1869 1786 83 3 312 512\n-/+ buffers/cache: 961 908 \nSwap: 4047 3 4044 "    }}
Here you can take the output from the output:
>>> stdout = test2["192.168.52.128" ["stdout"] total used free shared buffers cachedMem: 1869 1756 112 2 314 490-/+ buffers/cache: 951 917 Swap: 4047 4 4043
I wrote a script has a bug, that is, when specifying a set of host batch execution, the returned function, the storage content of only the last execution of the command of the host's information, do not have all the host's execution information storage, I hope the great God can solve this problem, and the generous enlighten!!
This article from the "Play God Clown" blog, reproduced please contact the author!
Ansible Python API 2.0 uses