Экспортирование zabbix templates

Экспортирование zabbix templates

В последнее время, я начал плотно изучать python и zabbix API для автоматизации различных процессов. Последнее что пришло на ум — это выполнить экспорт всех zabbix шаблонов.

Для этой цели, я создал скрипт:

# cat Export_Templates_from_Zabbix.py

Который имеет следующее содержание:

#!/bin/env python3
# -*- coding: utf-8 -*-
import requests
import time
import os
import xml.dom.minidom
import shutil

from datetime import datetime
from sys import exit
from pyzabbix import ZabbixAPI

class bgcolors:
    def __init__(self):
        self.get = {
            'HEADER': '\033[95m',
            'OKBLUE': '\033[94m',
            'OKGREEN': '\033[92m',
            'WARNING': '\033[93m',
            'FAIL': '\033[91m',
            'ENDC': '\033[0m',
            'BOLD': '\033[1m',
            'UNDERLINE': '\033[4m'
        }

def get_time():
    get_time = datetime.fromtimestamp(int(time.mktime(datetime.now().timetuple()))).strftime('%Y-%m-%dT%H:%M:%SZ')
    #print (get_time)
    return get_time

def login_to_zabbix():
    # host, login, password to connect to zabbix-server
    Zabbix_Host = 'https://zabbix.com/'
    Zabbix_User = 'apiuser'
    Zabbix_Password = 'oLEHbOeRDv0KxRSP'
    # You can use the Connection_Timeout
    Connection_Timeout = 25
    # Verify SSL
    Verify_SSL = False
    # Connect to zabbix-server
    zapi = ZabbixAPI(Zabbix_Host, timeout=Connection_Timeout)
    zapi.session.verify = Verify_SSL
    if not Verify_SSL:
        from requests.packages.urllib3.exceptions import InsecureRequestWarning
        requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    #
    zapi.login(Zabbix_User, Zabbix_Password)
    zapi.session.auth = (Zabbix_User, Zabbix_Password)
    # You can re-define Connection_Timeout after
    zapi.timeout = Connection_Timeout
    return zapi

def get_templates():
    templates = []
    zapi = login_to_zabbix()
    Get_Templates = zapi.template.get(output=['templateid', 'name'])
    for template in Get_Templates:
        templates.append(template)
    return templates

def export_templates():
    zapi = login_to_zabbix()
    templates = get_templates()
    dir_path = 'exported_templates'

    if not os.path.exists(dir_path):
        #shutil.rmtree(dir_path)
        os.makedirs(dir_path)

    for template in templates:
        template_id = template['templateid']
        template_name = template['name']

        rules = {
            "options": {
                "templates": [template_id]
                },
            "format": "xml"
         }
        template_name_out = dir_path + '/' + template_name + '.xml'
        result = zapi.do_request('configuration.export', rules)
        #print(result)
        template = xml.dom.minidom.parseString(result['result'].encode('utf-8'))
        date = template.getElementsByTagName("date")[0]
        # We are backing these up to git, steralize date so it doesn't appear to change
        # each time we export the templates
        #
        # add normal date here
        #
        now_time = get_time()
        date.firstChild.replaceWholeText(now_time)
        try:
            f = open(template_name_out, 'wb')
            #f.write(template.toprettyxml(indent='', newl='', encoding='UTF-8'))
            f.write(template.toprettyxml().encode('utf-8'))
            f.close()
            print (template_name + '.xml', 'file has been created')
        except Exception:
             print ('I cant write to file: ', Exception)
    return export_templates


def main():
    Start_Time = time.time()

    zapi = login_to_zabbix()
    Zabbix_Version = zapi.do_request('apiinfo.version')
    print(bgcolors().get['OKGREEN'],"============================================================", bgcolors().get['ENDC'])
    print(bgcolors().get['OKGREEN'],'Zabbix Version:', Zabbix_Version['result'] + bgcolors().get['ENDC'])
    print(bgcolors().get['OKGREEN'],"============================================================", bgcolors().get['ENDC'])

    export = export_templates()

    End_Time = round(time.time() - Start_Time, 2)
    print("--- %s seconds ---" % End_Time)

    print(bgcolors().get['OKGREEN'], "============================================================", bgcolors().get['ENDC'])
    print(bgcolors().get['OKGREEN'], "==========================FINISHED==========================", bgcolors().get['ENDC'])
    print(bgcolors().get['OKGREEN'], "============================================================", bgcolors().get['ENDC'])
if __name__ == '__main__':
    main()

Запускаем:

# python3 Export_Templates_from_Zabbix.py

Вывод получим:

 ============================================================
 Zabbix Version: 2.4.8
 ============================================================
Template OS Linux.xml file has been created
Template App Zabbix Server.xml file has been created
Template App Zabbix Proxy.xml file has been created
Template App Zabbix Agent.xml file has been created
Template SNMP Interfaces.xml file has been created
Template SNMP Generic.xml file has been created
Template SNMP Device.xml file has been created
Template SNMP OS Windows.xml file has been created
Template SNMP Disks.xml file has been created
Template SNMP OS Linux.xml file has been created
Template SNMP Processors.xml file has been created
Template IPMI Intel SR1530.xml file has been created
Template IPMI Intel SR1630.xml file has been created
Template App MySQL.xml file has been created
Template OS OpenBSD.xml file has been created
Template OS FreeBSD.xml file has been created
Template OS AIX.xml file has been created
Template OS HP-UX.xml file has been created
Template OS Solaris.xml file has been created
Template OS Mac OS X.xml file has been created
Template OS Windows.xml file has been created
Template JMX Generic.xml file has been created
Template JMX Tomcat.xml file has been created
Template Virt VMware.xml file has been created
Template Virt VMware Guest.xml file has been created
Template Virt VMware Hypervisor.xml file has been created
Template App FTP Service.xml file has been created
Template App HTTP Service.xml file has been created
Template App HTTPS Service.xml file has been created
Template App IMAP Service.xml file has been created
Template App LDAP Service.xml file has been created
Template App NNTP Service.xml file has been created
Template App NTP Service.xml file has been created
Template App POP Service.xml file has been created
Template App SMTP Service.xml file has been created
Template App SSH Service.xml file has been created
Template_role_App_Puppet.xml file has been created
Template_AWS_RDS.xml file has been created
--- 223.18 seconds ---
 ============================================================
 ==========================FINISHED==========================
 ============================================================

Конечно, некоторые вещи тут руками делаются. Но я постараюсь переписать их. Скрипт работает нормально, проверялся несколько раз.

Его можно закинуть в crontab, чтобы выполнялся бэкап автоматически. У меня появилась идея  — это в указанную папку, установить GIT, который будет коммитить (версионировать) ваши шаблоны в определенную, созданную ветку. При необходимости, можно будет смерджить в мастер (как вариант). Это даст возможность откатить все изменения до нужного состояния.

На этом у меня все, статья «Экспортирование zabbix templates» завершена.

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *