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

前言:

在自动化、批量化操作主机的时候,有时候咱们需要定义主机组。 比如,saltstack的group组,及salt-N参数,在ansible下的自己搞定ansible的主机组。有些麻烦,要知道,你既然选择了用saltstack、ansible这类的集群操作工具,如果你再选择把几十个多到几百个手动地,一个个地把主机组及相关联的主机写入配置,是不是显得很1+1。

这里简单说下我的一些个方法,首先可以避免这些个配置的写入,在产生minion的id的时候,就给他一个完美又规范的主机域名。 比如,bj-zw-nginx,很容易定位到北京,兆维,nginx机组。 其实主要你的主机域名相当的规范了,啥都好办了。 如果一些难搞的主机,非要自定义group,可以通过cmdb资产接口,来取值,然后复写到配置文件里面,这个方法很有效,在没有了解到ansible有动态inventory的功能前,我一直在用这个方法,间隔性的会从cmdb接口拿到最新的主机及配置信息,,复写到类hosts文件里面。

其实我上面说的功能,已经算是可以实现动态的hosts功能,看了沈灿和金山小伙的晓聪的讨论,才知道有个叫 Dynamic Inventory 的东西,这个功能其实是我上面讲解第二个方法的集成版,他省略了这一步,直接调用一个有inventory功能的脚本,然后取出相关的主机list,然后执行。

(这里打个广告,这两天通过朋友了解了猎豹那边的技术氛围,还不错,人虽然不多,因为是面向国外业务的团队,能力真心牛叉,那边运维研发的水平最少不比我差,欢迎牛人去猎豹面试,祝好运 !!! )

好了,正题!

原文:

我觉得官网有些太实在了,一些例子说的简单点就行,好让我们自己去扩展思维。 官网一上来就是cobbler和ec2的实例,谁看都有点麻。。。 我是真麻。

模拟从cmdb资产接口获取数据,然后返回json的脚本 getcmdb.py的内容

#!/usr/bin/python#xiaorui.ccimportargparseimportConfigParserimportosimportrefromtimeimporttimeimportxmlrpclibtry:importjsonexceptImportError:importsimplejsonasjsondefgood():parser=argparse.ArgumentParser(description=’ProduceanAnsibleInventoryfilebasedonCobbler’)parser.add_argument(‘–list’,action=’store_true’,default=True,help=’Listinstances(default:True)’)parser.add_argument(‘–host’,action=’store’,help=’Getallthevariablesaboutaspecificinstance’)printjson.dumps({“web”:{“hosts”:[“10.10.10.66”]}})classCobblerInventory(object):#原文:def__init__(self):”””Mainexecutionpath”””self.conn=Noneself.inventory=dict()#Alistofgroupsandthehostsinthatgroupself.cache=dict()#Detailsabouthostsintheinventory#ReadsettingsandparseCLIargumentsself.parse_cli_args()#Cacheifself.args.refresh_cache:self.update_cache()elifnotself.is_cache_valid():self.update_cache()else:self.load_inventory_from_cache()self.load_cache_from_cache()data_to_print=””#Datatoprintifself.args.host:data_to_print=self.get_host_info()elifself.args.list:#Displaylistofinstancesforinventorydata_to_print=self.json_format_dict(self.inventory,True)else:#defaultactionwithnooptionsdata_to_print=self.json_format_dict(self.inventory,True)printdata_to_printdef_connect(self):ifnotself.conn:self.conn=xmlrpclib.Server(self.cobbler_host,allow_none=True)…………尼玛太多了。defjson_format_dict(self,data,pretty=False):”””ConvertsadicttoaJSONobjectanddumpsitasaformattedstring”””ifpretty:returnjson.dumps(data,sort_keys=True,indent=2)else:returnjson.dumps(data)good()

脚本后面都是官网的cobbler的,大家可以直接摘出来。只需要上面的good函数就可以了。

任何业绩的质变都来自于量变的积累。

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

相关文章:

你感兴趣的文章:

标签云: