Ansible dynamic creation of the hosts list via the CMDB asset interface

Source: Internet
Author: User
Tags vars saltstack

Objective:

Sometimes we need to define a host group when automating and batching the operations master. For example, Saltstack group, and Salt-n parameters, in Ansible under the self-fix ansible of the host group. Some trouble, you know, since you choose to use Saltstack, ansible this kind of cluster operation tool, if you choose to put dozens of more than hundreds of manually, one after the host group and associated hosts write configuration, is not appear very.


Here are some of my methods, the first can avoid these configuration of the write, in the generation of Minion ID, give him a perfect and canonical host domain name. For example, Bj-zw-nginx, easy to locate Beijing, mega-dimensional, Nginx unit. In fact, the main name of your host domain is quite standardized, and everything is done. If some of the difficult host, do not want to customize the group, can be used through the CMDB asset interface, and then replication to the configuration file inside, this method is very effective, I have not learned that Ansible has dynamic inventory function before, I have been using this method, The interval will be from the CMDB interface to get the latest host and configuration information, replication into the class hosts file.


Actually I said above function, already can realize dynamic of the hosts function, saw Shen Zan and Jinshan small gang of Xiao Cong's discussion, just know have a called Dynamic Inventory thing, this function is actually I explain the second method integrated version, he omitted this step, Call a script with the inventory function directly, then remove the associated host list and execute.


(here to play an advertisement, these two days through friends know the cheetah side of the technical atmosphere, but also good, although not many, because it is a team for foreign business, the ability of the true cow fork, there is no difference in the level of research and development at least than I, welcome to the Cheetah interview, good luck!!! )


Okay, here's the point!

Original: http://rfyiamcool.blog.51cto.com/1030776/1416808

I think the official website is a bit too real, some examples of simple point, so that we can expand our thinking. The official website comes up is cobbler and EC2 instance, who looks a bit hemp ... I am a real hemp.



650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/29/FE/wKiom1OAwivQMfZdAAJjsCXI-gA948.jpg "title=" 111. JPG "alt=" wkiom1oawivqmfzdaajjscxi-ga948.jpg "/>


Simulates retrieving data from the CMDB asset interface and then returning the contents of the JSON script getcmdb.py

#!/usr/bin/python#xiaorui.ccimport argparseimport configparserimport osimport refrom  time import timeimport xmlrpclibtry:    import jsonexcept  Importerror:    import simplejson as jsondef good ():     parser = argparse. Argumentparser (description= ' produce an ansible inventory file based on  Cobbler ')     parser.add_argument ('--list ',  action= ' store_true ',  default=true,  help= ' list instances  (default: true) ')     parser.add_argument ('--host ',  action= ' store ',  help= ' get all the variables about a specific  Instance ')         print json.dumps ({"web": {"hosts": ["10.10.10.66" ]}}) Class cobblerinventory (object): #原文: HTTP://RFYIAMCOOL.BLOG.51CTO.COM/1030776/1416808 &NBSp;  def __init__ (self):         "" " Main  execution path  "" "        self.conn = None         self.inventory = dict ()   # a list  of groups and the hosts in that group         self.cache = dict ()   # Details about hosts in  the inventory        # read settings and  Parse cli arguments        self.parse_cli_args ()          # Cache        if  Self.args.refresh_cache:            self.update_ Cache ()          elif not self.is_cache_valid ():             self.update_cache ()         else:             self.load_inventory_from_cache ()              self.load_cache_from_cache ()          data_to_print =  ""         #  data to print        if self.args.host:             data_to_print = self.get_host_info ()         elif self.args.list:             # display list of instances for inventory      &nbSp;      data_to_print = self.json_format_dict (self.inventory,  True)         else:  # default action with  no options            data_to_print  = self.json_format_dict (self.inventory, true)          Print data_to_print    def _connect (self):         if not self.conn:             self.conn = xmlrpclib. Server (Self.cobbler_host, allow_none=true)     .... There are too many.     def json_format_dict (Self, data, pretty=false):          "" " Converts a dict to a JSON object and  dumps it as a formatted string  "" "        if  Pretty:            return json.dumps (data,  sort_keys=true, indent=2)         else:             return json.dumps (data) Good ()


Behind the script are the official website of the cobbler, we can directly pick out. All you need is the good function above.

Not only can the hosts list be returned, but you can also get the VARs variable and reference it.  My side uses the simplest example, the direct echo {{VARs}}.  In general, you can use the-M template module to push the configuration.   In fact, I personally feel that the inventory dynamic information and custom module facts in some way some functions are duplicated. In my personal opinion, for example, I am operating an nginx vhosts and upstream information group, this time with inventory dynamics and modules can be extracted from the CMDB asset system of relevant information, just inventory more accurate return, Need to execute these commands on those target hosts!


Reference VARs Variable:

In other words, my example here is quite simple, specific from the interface to fetch data, we use URLLIB2 to do it.

 #xiaorui. Ccdef good ():      parser =  argparse. Argumentparser (description= ' produce an ansible inventory file based on  Cobbler ')     parser.add_argument ('--list ',  action= ' store_true ',  default=true,  help= ' list instances  (default: true) ')     parser.add_argument ('--host ',  action= ' store ',  help= ' get all the variables about a specific  Instance ') #    print json.dumps ({"web": {"hosts": ["10.10.10.66"]},{"VARs": {"Todo": " This server whill restart "}}})     print json.dumps ({" web ": {" hosts ": [" 10.10.10.66 "]," VARs ": {" Todo ":" This server whill restart "}}," Nginx ": {" hosts ": [" 10.10.10.69 "]," VARs ": {" Todo ":" This nginx is restart "}}) 



650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/29/FE/wKiom1OAxf7BOS3IAAHZpc0tp5Y600.jpg "title=" ll.jpg "alt=" Wkiom1oaxf7bos3iaahzpc0tp5y600.jpg "/>


Notice the return format of ansible inventory, the Web is equivalent to the [web] title inside the/etc/ansible/hosts, and hosts are equivalent to the list,vars equivalent of a variable under the [web].  Of course these variables are supplied to the hosts host, referenced by JINJA2. In general, the return can not be executed correctly, because the format is not correct, if the format is right, no reason! (This is nonsense)

Example of the original hosts:

[atlanta]host1host2[raleigh]host2host3[southeast:children]atlantaraleigh[southeast:vars]some_server= Foo.southeast.example.comhalon_system_timeout=30self_destruct_countdown=60escape_pods=2[usa:children] Southeastnortheastsouthwestnorthwest


This is the JSON information that ansible can return via inventory.

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/29/FE/wKioL1OAxmmDZbKnAAC6YrUo8v8855.jpg "title=" Oooo.jpg "alt=" Wkiol1oaxmmdzbknaac6yruo8v8855.jpg "/>


to a more complete example:

#!/usr/bin/env pythonimport sqlite3import systry:    import jsonexcept  ImportError:    import simplejson as jsondbname =  '/etc/ Inv.db ' Def grouplist (conn):     inventory ={}    inventory[' Local '] = [  ' 127.0.0.1 '  ]    cur = conn.cursor ()      cur.execute ("Select type, name from hosts order by 1, 2")     for row in cur.fetchall ():         group = row[' type ']        if group is  none:            group =  ' ungrouped '                 if not  group in inventory:            inventory[group] =  {                 ' hosts '  : []            }         inventory[group][' hosts '].append (row[' name ')     cur.close ()     print json.dumps (inventory, indent=4) Def hostinfo (conn, name):     vars = {}    cur = conn.cursor ()      cur.execute ("Select count (*)  from hosts where name=?",  (name, ) )     row = cur.fetchone ()     if row[0] == 0:         print json.dumps ({})          sys.exit (0)     # inject some variables for all hosts     vars = {         ' admin '           :  ' Jane jolie ',         ' Datacenter '     : 1   &NBSP,} #从ldap重组数据     if  ' LDAP '  in name.lower ():         vars[' BaseDN '] =  ' Dc=mens , Dc=de '     print json.dumps (vars, indent=4) if __name__ ==  ' __main __ ':     con = sqlite3.connect (dbname)     con.row_factory= Sqlite3. Row    if len (SYS.ARGV)  == 2 and  (sys.argv[1] ==  '-- List '):         grouplist (Con)     elif len ( SYS.ARGV)  == 3 and  (sys.argv[1] ==  '--host '):         hostinfo ( CON, SYS.ARGV[2])     else:        print  "Usage: %s --list or --host 


Simply look at the format is not the same. Well, that's it, Ansible's Chinese documents are few, I really hope that these small text for everyone in the work to improve efficiency and some ideas to achieve.


This article comes from "Feng Yun, on her." "blog, declined reprint!"

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.