this script will scan the hosts_templates table and sync all hosts with their respective templates. if you only want to see what changes will be made without modifying the database, use the TESTRUN constant (highly recommended).
Code:
<?php
chdir('zabbix-1.1beta6/frontends/php'); // root of zabbix installation
include 'include/config.inc.php';
define('TESTRUN', 1); // if set to 1, database wont be modified
$USER_DETAILS = array(
'userid' => '3' // id of user with 'administrative' permissions
);
// *** delete non-template triggers ***
printf("deleting all non-template triggers\n");
if(!TESTRUN) {
DBexecute('delete triggers, functions from functions f, triggers t, items i, hosts h where f.triggerid=t.triggerid and f.itemid=i.itemid and i.hostid=h.hostid and h.status<>3');
}
// *** scan hosts_templates table ***
$result = DBselect('select * from hosts_templates');
while($row = DBfetch($result)) {
// *** delete orphaned hosts from hosts_templates table ***
$result2 = DBselect(sprintf("select host from hosts where hostid=%d limit 1", $row['hostid']));
if (!DBnum_rows($result2)) {
printf("host %d does not exist (deleting from hosts_templates table)\n", $row['hostid']);
if(!TESTRUN) {
DBexecute(sprintf("delete from hosts_templates where hostid=%d", $row['hostid']));
}
}
// *** sync all hosts with templates ***
else {
printf("syncing host %d with template %d\n", $row['hostid'], $row['templateid']);
if(!TESTRUN) {
sync_host_with_template($row['hostid'], $row['templateid'], $row['items'], $row['triggers'], $row['graphs']);
}
// *** get hosts's items ***
$host_items = array();
$result2 = DBselect(sprintf("select key_ from items where hostid=%d order by key_", $row['hostid']));
while($row2 = DBfetch($result2)) {
$host_items[] = $row2['key_'];
}
// *** get template's items ***
$template_items = array();
$result2 = DBselect(sprintf("select key_ from items where hostid=%d order by key_", $row['templateid']));
while($row2 = DBfetch($result2)) {
$template_items[] = $row2['key_'];
}
// *** show remaining host/template differences ***
$item_diff = array_diff($template_items, $host_items);
if (!empty($item_diff)) {
foreach ($item_diff as $this_element) {
printf("host %d is missing item %s from template %d\n", $row['hostid'], $this_element, $row['templateid']);
}
}
$item_diff = array_diff($host_items, $template_items);
if (!empty($item_diff)) {
foreach ($item_diff as $this_element) {
printf("host %d has non-template item %s\n", $row['hostid'], $this_element);
}
}
}
}
?>
Code:
$ php zabbix_check_template_linkage.php
)
Comment