Python API 2.0
In 2.0 things begin to be more complicated, but you will get more discrete and readable classes:
#!/usr/bin/env Pythonimport jsonfrom Collections import namedtuplefrom Ansible.parsing.dataloader Import Dataloaderfrom ansible.vars Import variablemanagerfrom ansible.inventory import Inventoryfrom Ansible.playbook.play Import playfrom ansible.executor.task_queue_manager import taskqueuemanagerfrom ansible.plugins.callback Import Callbackbaseclass Resultcallback (callbackbase): "" "Example callback plug-in for execution of results if you want to collect all the results to a single object for processing execution of the end, see the use of ' JSON ' callback plugin or write your own custom callback plugin "" "Def V2_RUNNER_ON_OK (self, result, **kwargs): "" "the JSON representation of the printed result the method can store the result in an instance property for later retrieval" " "host = Result._host print Json.dumps ({host.name:result._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= ' local ', module_path= '/path/to/mymodules ', forks=100, Become=none, Become_method=none, become_user= None, check=false) passwords = Dict (vault_pass= ' secret ') # instantiate our resultcallback to process the results in Results_callback = Resultcallback () # Create inventory and pass it to var managerinventory = Inventory (Loader=loader, Variable_manager=variable_manager, Host_ list= ' localhost ') variable_manager.set_inventory (inventory) # Create play with Tasksplay_source = dict (name = "Ansi Ble Play ", hosts = ' localhost ', gather_facts = ' no ', tasks = [Dict (action=dict (module= ' sh Ell ', args= ' ls '), 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 ITTQM = N ONETRY: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 ' Defaul T ' callback plugin) result = Tqm.run (play) Finally:if TQM is not None:tqm.cleanup ()
Python API Pre 2.0
This is simple:
Import Ansible.runnerrunner = Ansible.runner.Runner ( module_name= ' ping ', module_args= ' ', pattern= ' web * ', forks=10) datastructure = Runner.run ()
The Run method returns the results of each host, grouped according to whether it can be contacted. The return type is module-specific, as shown in the documentation for the module:
{ "Dark" : { "web1.example.com" " Failure Message " }, " contacted " : { "web2.example.com" : 1 }}
A module can return any type of JSON data, so ansible can be used as a framework to quickly build powerful applications and scripts.
Detailed API Examples
The following script prints out the uptime information for all hosts:
#!/usr/bin/pythonimport ansible.runnerimport sys# construct the Ansible runner and execute on all Hostsresults = ANSIBLE.R Unner. Runner ( pattern= ' * ', forks=10, module_name= ' command ', module_args= '/usr/bin/uptime ',). Run () if results is None: print "No hosts found" sys.exit (1) print "Up ***********" for (hostname, result) in results[' contacted ']. Items (): if not ' failed ' in result: print '%s >>>%s '% (hostname, result[' stdout ']) print "failed ******* "For (hostname, result) in results[' contacted '].items (): if ' failed ' in result: print '%s >>>%s '% (host Name, result[' msg ']) print "Down *********" for (hostname, result) in results[' Dark '].items (): print "%s >>> %s "% (hostname, result)
The advanced programmer may also want to read the source to the ansible itself, because it uses the API (with all available options) to implement the executable command-line tool (LIB/ANSIBLE/CLI/).
For more information, please refer to the official website: http://docs.ansible.com/ansible/latest/dev_guide/developing_api.html
Python Learning ansible API