溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python3連接mysql獲取ansible動(dòng)態(tài)inventory腳本

發(fā)布時(shí)間:2020-09-30 02:19:27 來(lái)源:腳本之家 閱讀:156 作者:獨(dú)孤清揚(yáng)@AlbertCQY 欄目:開(kāi)發(fā)技術(shù)

Ansible Inventory  介紹

Ansible Inventory 是包含靜態(tài) Inventory 和動(dòng)態(tài) Inventory 兩部分的,靜態(tài) Inventory 指的是在文件中指定的主機(jī)和組,動(dòng)態(tài) Inventory 指通過(guò)外部腳本獲取主機(jī)列表,并按照 ansible 所要求的格式返回給 ansilbe 命令的。這部分一般會(huì)結(jié)合 CMDB 資管系統(tǒng)、云計(jì)算平臺(tái)等獲取主機(jī)信息。由于主機(jī)資源一般會(huì)動(dòng)態(tài)的進(jìn)行增減,而這些系統(tǒng)一般會(huì)智能更新。我們可以通過(guò)這些工具提供的 API 或者接入庫(kù)查詢等方式返回主機(jī)列表。

腳本地址:https://github.com/AlbertCQY/scripts/tree/master/ansible

腳本用法:README.txt

1、腳本用法

bestpay用戶 cd /tools/scripts/ansible

python3.6 invscript.py -h

1)、查詢某個(gè)分組中包含哪些主機(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ù)庫(kù)主機(jī)列表,sql中最好對(duì)ip進(jìn)行去除空格并排序,否則可能會(huì)有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ù)中動(dòng)態(tài)獲取主機(jī)列表,動(dòng)態(tài)inventory,不用維護(hù)主機(jī)列表
-- Date : 2020/01
-- Author:陳晴陽(yáng)
Vervisons:
-- 20200106 1.0,陳晴陽(yáng),實(shí)現(xiàn)了動(dòng)態(tài)獲取主機(jī)列表,按照默認(rèn)互信方式獲取主機(jī)信息。
-- 20200116 2.0,陳晴陽(yáng),增加--group參數(shù),并統(tǒng)計(jì)各個(gè)分組主機(jī)個(gè)數(shù);重構(gòu)了group_all 所有主機(jī)按照各組設(shè)置的互信用戶來(lái)抓信息;增加對(duì)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)建每個(gè)分組
        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為元組,需要做個(gè)小轉(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 = []
      #查詢出來(lái)所有的主機(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動(dòng)態(tài)inventory腳本,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)億速云網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI