动态inventory脚本的python实现

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
基于python的动态inventory脚本实例
'''
import os
import sys
import argparse
try:
    import json
except ImportError:
    import simplejson as json
class ExampleInventory(object):

    def __init__(self):
        self.inventory = {}
        self.read_cli_args()
        #定义 --list 选项
        if self.args.list:
            self.inventory = self.example_inventory()
        elif self.args.host:
            self.inventory  = self.empty_inventory()
        else:
            self.inventory = self.empty_inventory()
        print json.dumps(self.inventroy);

    def eample_inventory(self):
        return {
            'group':{
                 'hosts':['0.0.0.0','1.1.0.1'],
                 'vars':{
                        'ansible_ssh_user':'test',
                        'ansible_ssh_private_key_file':'~/.test/insecure_private_key',
                        'example_varialbe':'value'
                }
             },
              '_meta':{
                   'hostvars':{
                        '0.0.0.10':{
                           'host_specific_var':'foo'
                        }  ,
                        '0.0.0.1': {
                            'host_specific_var' : 'bar'  
                       } 
                  }
               }
        }    

      def empty_inventory(self):
            return {'_meta':{'hostvars':{}}}  

      def read_cli_args(self):
              parser = argparse.ArgumentParser()
              parser.add_argument('--list',action = 'store_true')
              parser.add_argument('--host',action = 'store')
              self.args = parser.parser_args()

ExampleInventory()







                    
在尝试学习新的语言之前先理解这门语言的设计原理能够让你在探索这门新语言时保持一个清醒而且开发的状态。
原文地址:https://www.cnblogs.com/jackchen001/p/6684244.html