Using Zabbix API

Why is it necessary


During the implementation of zabbix to monitor the infrastructure, there was a need for the massive addition of sensors and triggers.
Using the web interface for this purpose did not bring any pleasure, it was painfully large amount of monotonous work and low speed on the way to happiness. For sim drew attention to the presence of zabbix api. For the purpose of mass adding sensors and other amenities of life, it seemed the most.

A brief analysis of the tools


A brief study showed that there are libraries in ruby, python and php.
PHP was discarded immediately, due to ignorance thereof, from the remaining languages, the choice fell on ruby. You can consider this a personal addiction, but as I work I use puppet tightly written in ruby, so I'm a little familiar with this language.
The Zabbix API uses JSON and JSON-RPC to integrate with third-party utilities and services.
As it turned out, this beast is not terrible, and upon closer examination it turned out to be simple enough to understand.
In order not to rack my brains much, the ready-made zabcon library was found. You
can see what it is like here.
We proceed directly to the recipe.

Initial task



There are a number of servers. On all servers there is a zabbix-agent. Sensors are required to monitor disk space; triggers are also required for these sensors. You can use templates, but for me this option does not seem flexible enough, again it is done through a web interface, to which a steady disgust arises after a couple of days of hard work.

It is better to lose the whole day, then fly in 5 minutes.



To solve the problem, we use the library provided by the zabcon utility.
Download, install dependencies, unzip.

Next, we draw a ruby ​​script with the following contents.

#!/usr/bin/ruby
#
require './zabbixapi.rb'
 
zbx=ZbxAPI.new('http://zabbix.server.com')
zbx.login('login','password')

# trigger
HIGH=4
AVERAGE=3
WARNING=2
INFORMATION=1

ENABLE=0
DISABLE=1

# return hostid
def hostid_from_hostname(hostname,zabbix)
 for host in zabbix.host.get({"extendoutput"=>true,'pattern'=>"#{hostname}"})
     return host['hostid']
 end
end

def add_disk_check(hostname,zabbix)
 # получаем диски с сервера, ssh настроен по ключам
 ssh=`ssh -o "StrictHostKeyChecking no" -q #{hostname} 'df -l -P -h | tail -n +2' `

 hostid=hostid_from_hostname(hostname,zabbix)
 for l in ssh
    disk=l.split[5].gsub("/","\/")
    name="API Free diskspace on #{disk}"

    item_p = {
     'description'=>name,
     'key_'=>"vfs.fs.size[#{disk},pfree]",
     'hostid'=>hostid,
     'type'=>'0',
     'data_type'=>0,
     'value_type'=>0,
     'units'=>"%"
    }

    begin
     uid = zabbix.item.create(item_p)
     p "cant create item on #{hostname} disk #{disk}" if uid.nil?
    end

    expression="{#{hostname}:vfs.fs.size[#{disk},pfree].last(0)}<10"
    description="API Free diskspace on {HOSTNAME} volume #{disk}"

    item_t={
         'hostid' => hostid,
         'expression'=>expression,
         'description'=>description,
         'priority'=>HIGH,
         'status'=>ENABLE,
    }

    begin
     uid = zabbix.trigger.create(item_t)
     p "cant create trigger on #{hostname} disk #{disk}" if uid.nil?
    end

 end
end

# Дальше пройдемся по всем серверам имеющимся в zabbix и добавим требуемые датчики с тригерами
for host in zbx.host.get({"extendoutput"=>true})
 id=host['hostid']
 hostname=host['host']
 puts "#{id} -- #{hostname}"
 add_disk_check(hostname,zbx)
end

# the end

* This source code was highlighted with Source Code Highlighter.



In the course of activity, I had to fix zabbixapi.rb, in the original version the script fell out if the required sensor or trigger was already present.
In the do_request function, we look for the following piece of code:
    if !resp["error"].nil?
      raise ZbxAPI_GeneralError, resp["error"] # закоментировать
    end
    
                return resp
             rescue Redirect                  # закоментировать
                redirects+=1
                     retry if redirects<=5
                     raise ZbxAPI_GeneralError, "Too many redirects"
             end

* This source code was highlighted with Source Code Highlighter.

we comment on the specified lines.

Summary


The work on surfing the web interface of the zabbix server was replaced by research activities, along the way a toolkit was drawn allowing to quickly adjust the monitoring to fit your own needs.
This example shows the flexibility and resourcefulness of a person in an attempt to get rid of routine work.

Also popular now: