ansible@ An effective configuration management tool--ansible Configure management--translation (12)

Source: Internet
Author: User
Tags rowcount

If there is no written authorization, please do not reprint the fifth chapter of your own definition module

External Inventoriesin The first chapter we saw how Ansible needs an inventory file, so that it knowswhere it hosts is a nd how to access them. Ansible also allows you to specify Ascript this allows you to fetch the inventory from another source. Externalinventory scripts can be written in any language that's like as long as theyoutput valid JSON. An external inventory script have to accept the different calls from Ansible. If Calledwith–list, it must return a list of all the available groups and the hosts in them. Additionally, it may is called with--host. In this case, the second argument would BEA hostname and the script is expected to return a list of variables for that host . All theoutputs is expected in JSON and so is should use a language that supports it naturally.

List of external inventory devices

The first chapter describes the implementation of Ansible requires a device inventory file. Let him know that they need access to those mainframe devices. Ansible is also able to script you to choose a different inventory file, which can be written in any language, just to match his output format to JSON.


Scripts for external inventory lists are required to accept 2 kinds of ansible calls. Assume that it is called with--list. It returns a list of groups and hosts that can be used. If called with--host, a list of available hosts is returned.

All the output must be in JSON format, so the language you use is best to support this format easily.

Let's write a module that takes a CSV file listing all your machines and presentsthis to Ansible as an inventory. This would be the handy if you had a CMDB that allowsyou to the export your machine list as CSV, or for someone who keeps records Oftheir machines in Excel. Additionally, it doesn ' t require any dependencies Outsidepython, as a CSV processing module are already included with Pytho N. This really justparses the CSV file to the right data structures and prints them out as JSON datastructures. The following is a example CSV file we wish to process; Wishto Customize it for the machines in your environment:group,host,variablestest,example,ansible_ssh_user= Roottest,localhost,connection=local

Let's write a CSV file that extracts data from all of your machines. Then publish the module to the Ansible inventory list. Suppose you have a CMDB (database) that you can use to export your device to CSV, or if the device record is stored in an Excel table, this module is very useful.

In addition, it does not require any dependencies other than Python, it only needs to parse the CSV file and then output the data in JSON format. Here is a sample of the CSV file we would like to work with, and you can define your own machine in your own environment:

Group,host,variables
Test,example,ansible_ssh_user=root
Test,localhost,connection=local

This file needs to is converted into the different JSON outputs. When--list iscalled, we need to output the whole thing in a form that looks like this:{"test": ["Example", "localhost"]}a nd when it's called with the arguments--host example, it should return this:{"Ansible_ssh_user": "Root"}here is the SCR IPT that opens a file named Machines.csv and produces the dictionaryof the groups if--list is given. Additionally, when given--host and a hostname,it parses that host ' s variables and returns them as a dictionary. The script is well-commented, so you can see what it is doing. You can run the script manually withthe--list and--host arguments to confirm that it behaves correctly.

This file needs to be converted into 2-format JSON output, when called with--list, like this:

{"Test": ["Example", "localhost"]}

When called with--host. Such

{"Ansible_ssh_user": "Root"}

The following script example opens a file called Machines.csv. When calling--list, it represents the group in a dictionary, and when called with--host, it represents the host and their variables in a dictionary.

The script has been very well gazed. You can use the--list and--host two parameters to test:

#!/usr/bin/env python#-*-coding:utf-8-*-import sysimport csvimport jsondef getlist (csvfile): # Init Local Variables #初始化本地变量 glist = dict () rowcount = 0 # Iterate over all the rows #历遍全部的行 for row in CSVFile: # T Hrow away the header (row 0) #去掉第一行, header row if rowcount! = 0: # Get The values out of the row #获取非  header row data (group, host, variables) = row # If This is the first time we ' ve # Read this group                Create a empty # list for it #假设第一次读这个组, give him a new list if group not in Glist: Glist[group] = list () # ADD the host to the list #把主机加到这个列表中 Glist[group].ap Pend (Host) # Count The rows we ' ve processed #计算我们已经处理的行 rowcount + = 1 Retu    RN Glistdef GetHost (CSVFile, host): # Init Local variables #初始化本地变量 rowcount = 0 # Iterate over all the rows #历遍全部行 for Row in CSvfile: # Throw away the header (Row 0) #去掉标题行 if rowcount! = 0 and row[1] = = Host: # Get the values O  UT of the row #获取非标题行的数据 variables = dict () for Kvpair in Row[2].split (): Key, Value = kvpair.split (' = ', 1) variables[key] = value return variables # Count the rows we ' ve processed #计算我们已经处理的行数量 rowcount + = 1command = sys.argv[1] #Open The CSV and start parsing it# Open the CSV file, start at        Manager with open (' Machines.csv ', ' R ') as Infile:result = Dict () CSVFile = Csv.reader (infile) if command = = '--list ': result = GetList (csvfile) elif Command = = '--host ': result = GetHost (CSVFile, sys.argv[2]) print JSON.D Umps (Result)


You can now use this inventory script to provide the inventory when using ANSIBLE.A quick-to-test that everything is W Orking correctly is to use the Ping module totest the connection to all the machines. This command won't test whether the hostsare in the right groups; If you want to does, you can use the same ping Modulecommand but instead of running it across all, you can simply use T He group youwould like to test.$ ansible-i csvinventory-m Ping All

Now you can use this script to provide a list of inventory lists when you use Anisbile. Use the ping module to connect all the machines in the list to test if the script is performing well.

When the host is not in his group, it will fail. Just you can ping it alone and try it. Use groups to test the commands such as the following:

$ ansible-i csvinventory-m Ping All

Similar to when you used the ping module in Chapter 1, Getting Started with ansible,you should see a output that looks Li Ke the Following:localhost | Success >> {"Changed": false, "ping": "Pong"}example | Success >> {"Changed": false, "ping": "Pong"}this indicates that's can connect and use Ansible on all the hosts fro M yourinventory. You can use the Same-i argument with Ansible-playbook to run Yourplaybooks with the same inventory.
Same as the first chapter. The output looks like this:

localhost | Success >> {
"Changed": false,
"Ping": "Pong"
}
Example | Success >> {
"Changed": false,
"Ping": "Pong"
}


You can connect all the machines in the list. You can also use the-I parameter to perform playbook.

Summaryhaving read this chapter your should now is able to build modules using either bashor any other languages so you K Now. You should is able to install modules that youhave either obtained from the Internet, or written yourself. We also covered how Towrite modules more efficiently using the boilerplate code in Python. Finally, we wrotean inventory script that allows-your inventory from the external source.

Summary of this chapter

After reading this chapter, you should be able to use bash or other language, you will create your own custom module, will install the module, you download from the Internet, or write it yourself. We also learned how to use Python boilerplate code to write modules efficiently.

Finally. We have written a script that allows you to count inventory quotations from external files.

[email protected] An effective configuration management tool--ansible Configure management--translation (12)

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.