killerxf 发表于 2018-7-30 13:16:41

ansible通过cmdb资产接口动态创建hosts列表

#!/usr/bin/python  
#xiaorui.cc
  
import argparse
  
import ConfigParser
  
import os
  
import re
  
from time import time
  
import xmlrpclib
  

  
try:
  
    import json
  
except ImportError:
  
    import simplejson as json
  

  
def 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
  
    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
  
            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)
  

  
    ............尼玛太多了。
  
    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()

jxcia 发表于 2018-8-1 16:59:59

大兄弟 求视屏分享
页: [1]
查看完整版本: ansible通过cmdb资产接口动态创建hosts列表