As it's always easier to understand things when you see a working example, I have added a simple example that you can use to create hosts, link them to a template and add them to the correct group.
For this recipe, we only need our Zabbix server with the super administrators account that was created at the installation. We need to install the Zabbix agent on the Zabbix server. There is no need to change any of the parameters just make sure that the Zabbix server is monitored by Zabbix. Once it is working, remove the Zabbix server host from the list of hosts in Zabbix as we will add it again by making use of the API.
pip
on our machine installed:yum install http://fedora.cu.be/epel/6/i386/epel-release-6-8.noarch.rpm
python
and python-pip
on your Zabbix server as follows:yum install python python-pip
pip install pyzabbix
zabbix_host_add.py
with vi
or another editor and copy the following code into this file and save it.#!/usr/bin/python from pyzabbix import ZabbixAPI # IP of the Zabbix server ZABBIX_SERVER = 'http://127.0.0.1/zabbix' # Host Parameters host_name='Zabbix server' ip='127.0.0.1' group='Zabbix servers' template='Template App Zabbix Server' port=10050 login='Admin' password='zabbix' zapi = ZabbixAPI(ZABBIX_SERVER) # Login to the Zabbix API zapi.login(login, password) group_id = zapi.hostgroup.getobjects(name=group)[0]['groupid'] template_id = zapi.template.getobjects(name=template)[0]['templateid'] print(group_id) print(template_id) zapi.host.create ( { "host": host_name, "interfaces":[{ "type":1, "dns":"", "main":1, "ip": ip, "port": port, "useip": 1, }], "groups": [{ "groupid": group_id }], "templates": [{ "templateid": template_id }], }) print('Host Added')
python zabbix_host_add.py
When the script has run, you should see some output with the groupid
and the templateid
parameters and at the last line you will get a message that says: 'Host Added'
.
Now let's go to Zabbix to Configuration | Hosts and you should see your Zabbix server back in the list linked with the correct Zabbix template added to the correct group Zabbix servers.
By making use of PyZabbix, we added a host to our Zabbix server in an easy way. First we defined some parameters such as username, password, hostname, hostgroup, and template. Then we told PyZabbix to authenticate us on the Zabbix server through the API. PyZabbix then gathered the correct ID information for the template and the group we had specified. Next we launched zapi.host.create
file with all the parameters specified that are necessary to create a new host.