python3連接mysql獲取ansible動態(tài)inventory腳本
Ansible Inventory 介紹
Ansible Inventory 是包含靜態(tài) Inventory 和動態(tài) Inventory 兩部分的,靜態(tài) Inventory 指的是在文件中指定的主機(jī)和組,動態(tài) Inventory 指通過外部腳本獲取主機(jī)列表,并按照 ansible 所要求的格式返回給 ansilbe 命令的。這部分一般會結(jié)合 CMDB 資管系統(tǒng)、云計算平臺等獲取主機(jī)信息。由于主機(jī)資源一般會動態(tài)的進(jìn)行增減,而這些系統(tǒng)一般會智能更新。我們可以通過這些工具提供的 API 或者接入庫查詢等方式返回主機(jī)列表。
腳本地址:https://github.com/AlbertCQY/scripts/tree/master/ansible
腳本用法:README.txt
1、腳本用法
bestpay用戶 cd /tools/scripts/ansible
python3.6 invscript.py -h
1)、查詢某個分組中包含哪些主機(jī),oracle_nj_all為inventory_group.py中的組名
python3.6 invscript.py --group oracle_nj_all
2)、查詢所有
python3.6 invscript.py --list
3)、查詢某分組主機(jī)中主機(jī)名,腳本也可以在play-book中使用-i指定inventory
ansible -i invscript.py mysql_nj_all -m shell -a “hostname”
2、更新數(shù)據(jù)庫主機(jī)列表,sql中最好對ip進(jìn)行去除空格并排序,否則可能會有warning
inventory_group.py中格式:
mygrp2就是ansible使用的組名
‘ssh_user':‘root' root用戶代表連到目標(biāo)主機(jī)的用戶。如果ansible server主機(jī)的test用戶和目標(biāo)的root用戶有互信,那么ansible腳本在test用戶下執(zhí)行。
例子如下:
mygrp2 = {‘sql':""" select ‘1.1.3.8' as ips union all select ‘1.1.3.112' as ips union all select ‘1.1.3.113' as ips “”", ‘ssh_user':‘root'}
部分腳本內(nèi)容:
#!/usr/bin/env python #-*- coding: UTF-8 -*- # ========================================================================= """ -- File Name : invscript.py -- Purpose : 從mysql數(shù)據(jù)中動態(tài)獲取主機(jī)列表,動態(tài)inventory,不用維護(hù)主機(jī)列表 -- Date : 2020/01 -- Author:陳晴陽 Vervisons: -- 20200106 1.0,陳晴陽,實現(xiàn)了動態(tài)獲取主機(jī)列表,按照默認(rèn)互信方式獲取主機(jī)信息。 -- 20200116 2.0,陳晴陽,增加--group參數(shù),并統(tǒng)計各個分組主機(jī)個數(shù);重構(gòu)了group_all 所有主機(jī)按照各組設(shè)置的互信用戶來抓信息;增加對IP地址排序功能。 """ # ========================================================================= import argparse import sys import json import settings import inventory_group as invgrp from connect_mysql import Mysql_Conn class DynamicInventory(object): def read_cli(self): parser = argparse.ArgumentParser() parser.add_argument('--host', nargs=1) parser.add_argument('--list', action='store_true') parser.add_argument('--group') self.options = parser.parse_args() def GetItemList(self): list_item = [] for item in dir(invgrp): if not item.startswith("__"): list_item.append(item) return list_item def GetGrpList(self): list_grpinfo = [] list_item = self.GetItemList() for item in list_item: itemcontent = getattr(invgrp, item) tmp_dic = {} tmp_dic[item] = itemcontent list_grpinfo.append(tmp_dic) return list_grpinfo def get_groups(self): hostgroups = self.GetGrpList() #allhost = [] for hostdic in hostgroups:#hostgroup為字典 for hostgroup in hostdic: #獲取字典的key self.result[hostgroup] = {} v_sql = hostdic[hostgroup]['sql'] #獲取sql v_ssh_user = hostdic[hostgroup]['ssh_user'] # 獲取sql hosts = self.connection.execsql(v_sql) #print(hosts) # 構(gòu)建每個分組 grp_host_list = [host[0] for host in hosts] grp_host_list = sorted(grp_host_list, key=lambda x: (int(x.split('.')[0]), int(x.split('.')[1]), int(x.split('.')[2]))) #排序 self.result[hostgroup]['hosts'] = grp_host_list self.result[hostgroup]['vars'] = {'ansible_ssh_user': v_ssh_user} #構(gòu)建_meta,注意ip為元組,需要做個小轉(zhuǎn)換ip[0] 需要字符串值 for ip in hosts: tmp_dic = {} tmp_dic['ansible_ssh_host'] = ip[0] self.result['_meta']['hostvars'][ip[0]] = tmp_dic # 構(gòu)建group_all self.result[self.defaultgroup]['hosts']=[] self.result[self.defaultgroup]['children'] =self.GetItemList() return self.result def get_host(self,ipaddr): ip = '' for i in ipaddr: ip = i data = {'ansible_ssh_host': ip} return data def get_group_hosts(self,grpname): if grpname == 'group_all': allhosts = [] #查詢出來所有的主機(jī)列表 hostgroups = self.GetGrpList() for hostdic in hostgroups: # hostgroup為字典 for hostgroup in hostdic: # 獲取字典的key v_sql = hostdic[hostgroup]['sql'] # 獲取sql hosts = self.connection.execsql(v_sql) allhosts.extend([host[0] for host in hosts]) allhosts = set(allhosts) # 去重 allhosts = sorted(allhosts, key=lambda x: (int(x.split('.')[0]), int(x.split('.')[1]), int(x.split('.')[2]))) #排序 cnt = 0 for i in allhosts: print(cnt + 1, i) cnt = cnt + 1 print('Group ' + grpname + ' Total hosts:', cnt) else: txt_grp ='invgrp.'+grpname+"""['sql']""" v_sql = eval(txt_grp) #這里偷懶用了邪惡函數(shù)eval hosts = self.connection.execsql(v_sql) cnt = 0 for i in hosts: print(cnt + 1,i[0]) cnt = cnt + 1 print('Group '+grpname+' Total hosts:',cnt) def __init__(self): try: self.connection = Mysql_Conn(settings.my_usr, settings.my_pass, settings.my_ip, settings.my_port, settings.my_db) except Exception as err: print("connect wrong", err) self.defaultgroup = 'group_all' self.options = None self.read_cli() self.result = {} self.result[self.defaultgroup] = {} self.result[self.defaultgroup]['hosts'] = [] self.result[self.defaultgroup]['vars'] = {'ansible_ssh_user': 'bestpay'} self.result['_meta'] = {} self.result['_meta']['hostvars'] = {} if self.options.host: data = self.get_host(self.options.host) print(json.dumps(data,indent=4)) elif self.options.list: data = self.get_groups() print(json.dumps(data,indent=4)) elif self.options.group: data = self.get_group_hosts(self.options.group) else: sys.exit("usage: --list or --host HOSTNAME or --group GROUPNAME") if __name__ == '__main__': DynamicInventory()
總結(jié)
以上所述是小編給大家介紹的python3連接mysql獲取ansible動態(tài)inventory腳本,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
Python調(diào)用騰訊API進(jìn)行人像動漫化效果實例
最近上網(wǎng)的時候看到了一個有趣的東西,叫做人物動漫化,嘗試著用python實現(xiàn)了,所以下面這篇文章主要給大家介紹了關(guān)于Python調(diào)用騰訊API進(jìn)行人像動漫化效果的相關(guān)資料,需要的朋友可以參考下2023-06-06Python qqbot 實現(xiàn)qq機(jī)器人的示例代碼
這篇文章主要介紹了Python qqbot 實現(xiàn)qq機(jī)器人的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07Python利用psutil獲取CPU與內(nèi)存等硬件信息
psutil是Python的一個第三方庫,提供了各種強大的硬件信息查閱功能,這篇文章主要為大家介紹了如何利用psutil獲取CPU與內(nèi)存等硬件信息,需要的可以參考一下2023-07-07