Python Learning ansible API

Source: Internet
Author: User
Tags dataloader

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

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.