最近在做zabbix的二次开发;发现zabbix在做自动化方便提供了强悍的支持,下面分享下CMDB和zabbix打通,把CMDB平台里面的所有机器同步到zabbix数据库,然后进行批量的模板绑定:
开发环境:
zabbix :2.4
python:flask框架.前端bootstrap,jquey:
实现思路:
一、
在CMDB表和ZAbbix主机表里面建立第三张管理的表(定义叫缓存表);利用zabbix API把数据库里面的host插入到第三张缓存表;然后通过和CMDB库里面的比较把没有在缓存表里的数据插入到缓存表,再同步到zabbix 数据库。
二、
绑定模板使用host.update 这个API,但是这个API在绑定后面的模板之后会删除已经绑定的模板,所以这里我们先遍历出前面所有的模板,然后把前面和后面的一起绑定。
缓存表的models结构:
class ZbHost(db.Model):
__tablename__ = 'zbhost'
id = db.Column(db.Integer, primary_key=True)
cmdb_hostid = db.Column(db.Integer, index=True, unique = True)
hostid = db.Column(db.Integer, index=True, unique = True)
host = db.Column(db.String(50))
ip = db.Column(db.String(32))
获取数据:
def init_cmdb():
#取host (在server表里)
hosts = api_action("server.get")
for h in hosts:
data = {'cmdb_hostid':h['id']}
db.session.query(ZbHost).filter_by(ip=h['inner_ip']).update(data)
db.session.commit()
#更新到cache表, ip
def init_zabbix():
#第一步 取出所有host,要ip,host,id
zb_hosts = zabbix_server.get_hosts()
zb_hosts_interface = zabbix_server.get_interface([z['hostid'] for z in zb_hosts])
# data = []
for h in zb_hosts:
h['ip'] = zb_hosts_interface[h['hostid']]
# data.append(h)
###数据插入数据库
db.session.add(ZbHost(**h))
db.session.commit()
同步主机到zabbix:
@main.route("/resource/monitor/ajax/sync_host_to_zabbix", methods=['POST'])
def sync_host_to_zabbix():
#接收参数
#hostid groupid
if request.method == "POST":
from app.common.zabbix import create_zabbix_host
params = dict(request.form)
hostids = params['hostids'][0].split(',')
ret = create_zabbix_host(hostids=params['hostids'][0].split(','),groupid=params['groupid'][0])
if len(ret) == len(hostids):
return '1'
else:
return json.dumps(ret)
return "500"
zabbix 界面:
到这里同步主机完成;下面的批量绑定模板:
def link_template(self, hostid, templateids):
templates = []
for id in templateids:
templates.append({"templateid": id})
print templates
print hostid
try:
ret = self.zb.host.update(hostid=hostid, templates=templates)
return ret
except Exception as e:
return e.message
视图:
@main.route("/monitor/ajax/link_zabbix_template", methods=['POST'])
def link_zabbix_template():
from app.common.zabbix import link_template
if request.method == "POST":
#1、获取前端数据
params = dict(request.form)
#{'hostids': [u'10106'], 'template_ids': [u'10001']}
hostids = params['hostids'][0].split(',')
template_ids = params['template_ids'][0].split(',')
ret_data = link_template(hostids, template_ids)
error = None
for r in ret_data:
try:
hostids.remove(r['hostids'][0])
except Exception, e:
error = e.message
if not hostids:
return "1"
else:
return error
return "500"
主机绑定模板:
绑定之后:
登录zabbix查看:
到此zabbix基本的同步主机,绑定模板已经完成;zabbix提供了非常优秀的API,我们可以用来实现很多我们需要的功能;上面的步骤已经基本上完成了我们日常说需要的功能;当然还有解绑模板删除主机,添加维护周期等等;