一、动态Inventory的作用
在实际生产应用中,经常会遇到业务的快速发展或者流量的急剧增加等情况,需要在短时间内向架构中添加几十台甚至上百台服务器来提高整个架构的处理能力,这个时候,手动管理Inventory文件不仅没有效率,而且非常泛味。
二、动态Inventory python代码
#! /usr/bin/env python3
import os
import sys
import argparse
try:
import json
except ImportError:
import simplejson as json
class ExampleInventory(object):
# 读取并分析读入的选项和参数
def read_cli_args(self):
parser = argparse.ArgumentParser()
parser.add_argument('--list', action='store_true')
parser.add_argument('--host', action='store')
self.args = parser.parse_args()
# 用于展示效果的JSON格式的Inventory文件内容
def example_inventory(self):
return {
'songxin': {
'hosts': ['10.3.150.199', '10.3.150.200','10.3.150.201','10.3.152.78'],
},
'_meta': {
'hostvars': {
'10.3.150.199': {
"ansible_ssh_user": "cedar",
"ansible_ssh_port": "52222"
},
'10.3.150.200': {
"ansible_ssh_user": "cedar",
"ansible_ssh_port": "52222"
},
'10.3.150.201': {
"ansible_ssh_user": "cedar",
"ansible_ssh_port": "52222"
},
'10.3.152.78': {
"ansible_ssh_user": "root",
"ansible_ssh_port": "22"
}
}
}
}
# 返回仅用于测试的空Inventory
def empty_inventory(self):
return {'_meta': {'hostvars': {}}}
def __init__(self):
self.inventory = {}
self.read_cli_args()
#定义'--list'选项
if self.args.list:
self.inventory = self.example_inventory()
#定义'--host[hostname]'先项
elif self.args.host:
self.inventory = self.empty_inventory()
#如果没有主机组或变量要设置,就返回一个空Inventory
else:
self.inventory = self.empty_inventory()
print(json.dumps(self.inventory))
ExampleInventory()