Ansible Playbook API Development Call test

Source: Internet
Author: User
Tags ansible playbook

Ansible is a lightweight batch configuration management tool for agentless, because of the relatively late (13) development based on ansible less relevant documents, so here are some small experiments, combined with the existing data and source code, explore the Ansible two times development.

The contents of the essay are divided into three parts.

    1. Playbook Edit Execution
    2. Python invokes API execution playbook
    3. Java calls the Python program for playbook execution

The experimental environment is centos6,ansible version is 1.9.4,python version is 2.6.6,JDK version is 1.7u79

First, playbook Edit execution

To edit playbook, the function here is to copy a script to the specified node and execute it, noting the format of Yaml, Note Indent


1 ---2 3 -Name:hostname4 5 hosts: "{{host}}"6 7 Sudo:yes8 9 tasks:Ten  One -name:copy file to "{{host}}" A  - copy:src=/tmp/ dest=/tmp/ mode=0775 -  the     -  - -Name:execute WebAuth -  +Script:/tmp/

If you want to run the playbook, you can use

# ansible-playbook/opt/ansible/webauth.yml--extra-vars ' host= ' nodes '

The results will be returned at this time.

PLAY [hostname] ***************************************************************Gathering FACTS***************************************************************OK: [] TASK: [CopyfileTo"{{host}}"] ***********************************************OK: [] TASK: [Execute WebAuth]*******************************************************changed: [] PLAY RECAP******************************************************************** ok=3Changed=1unreachable=0Failed=0

The ability to perform a successful description of playbook is no problem, if reported wrong, then follow the prompts to modify.

Second, Python invokes API execution playbook

The following uses Python to invoke API interface execution above playbook

1 Python code: test.py2 ImportSYS3 ImportAnsible.playbook4  fromAnsibleImportCallbacks5  fromAnsibleImportUtils6 7Stats =callbacks. Aggregatestats ()8PLAYBOOK_CB = callbacks. Playbookcallbacks (verbose=Utils. verbosity)9RUNNER_CB = callbacks. Playbookrunnercallbacks (stats, verbose=Utils. verbosity)Ten defExecute (play,params): OnePB =Ansible.playbook.PlayBook ( Aplaybook=Play, -stats=stats, -callbacks=PLAYBOOK_CB, therunner_callbacks=RUNNER_CB, -check=False, -extra_vars=eval (params) -   ) +   PrintPB - () + if __name__=='__main__': ARes=execute (sys.argv[1],sys.argv[2]) at   PrintRes

The Playbook=play in the code is given by the command line the Playbook script path that needs to be executed, stats is the process state used to collect execution, PLAYBOOK_CB is the result of PLAYBOOK_CB to output execution, Runner_ The callbacks is used to output the results of the playbook execution period.


' {"host": "Cloudeploy-nodes"} '

return Result:

PLAY [hostname] ***************************************************************Gathering FACTS***************************************************************OK: [] TASK: [CopyfileTo"{{host}}"] ***********************************************changed: [] TASK: [Execute WebAuth]*******************************************************OK: []{'': {'Unreachable':0,'skipped':0,'OK':2,'changed':1,'Failures':0}}

Third, Java calls Python program for playbook execution

Use Java to invoke Python for Java execution playbook

1;2 3;4 5;6 7;8 9  Public classtest{Ten  One    Public Static voidMain (String args[])throwsioexception{ A  -String command= "python/opt/ansible/ {' host ': '" +args[0]+ "'}"; -  theProcess Process =runtime.getruntime (). exec (command); -  - PrintStream (Process.getinputstream ()); -  + PrintStream (Process.geterrorstream ()); -  +System.out.println ("Finish"); A  at   } -  - Private Static voidPrintStream (InputStream inputstream) { -  -   if(InputStream = =NULL){ -  inSYSTEM.OUT.PRINTLN ("Input null"); -  to     return; +  -   } the  *String line = ""; $ Panax Notoginseng     Try(BufferedReader input =NewBufferedReader (NewInputStreamReader (InputStream))) -  the     { +  A        while(line = Input.readline ())! =NULL) { the  + System.out.println (line); -  $       } $  -}Catch(IOException E1) { -  theSystem.out.println ("output stream failed" +E1); - Wuyi e1.printstacktrace (); the  -     } Wu  -   } About  $}


#java Test Cloudeploy

The path to the playbook is fixed and can be passed in as a parameter.

Execution Result:

PLAY [hostname] ***************************************************************Gathering FACTS***************************************************************OK: []task: [Returnhostname] *******************************************************changed: []task: [CopyfileTo"{{host}}"] ***********************************************OK: []task: [Execute WebAuth]*******************************************************changed: []{'': {'Unreachable':0,'skipped':0,'OK':4,'changed':2,'Failures':0}}finish

Indicates successful execution, viewing the corresponding node, the file will be copied and executed


Github:playbook Source:

Kisips:ansible Document Playbook Advanced:

361way:ansible Section 10 ansible API

Stackoverflow:running Ansible-playbook using Python API Running-ansible-playbook-using-python-api

Ansible:developing API

Google:ansible Forum Https://!topic/ansible-project/V1PoNJcXV_w

Ansible Playbook API Development Call test

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: 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.