Implemented #73

This commit is contained in:
TheNetworkGuy 2024-07-25 15:47:09 +02:00
parent 91796395ef
commit 70a5c3e384
3 changed files with 55 additions and 29 deletions

View File

@ -94,6 +94,8 @@ Setting the `create_hostgroups` variable to `False` requires manual hostgroup cr
The format can be set with the `hostgroup_format` variable. The format can be set with the `hostgroup_format` variable.
Any nested parent hostgroups will also be created automatically.
Make sure that the Zabbix user has proper permissions to create hosts. Make sure that the Zabbix user has proper permissions to create hosts.
The hostgroups are in a nested format. This means that proper permissions only need to be applied to the site name hostgroup and cascaded to any child hostgroups. The hostgroups are in a nested format. This means that proper permissions only need to be applied to the site name hostgroup and cascaded to any child hostgroups.

View File

@ -312,9 +312,9 @@ class NetworkDevice():
self.logger.warning(e) self.logger.warning(e)
raise SyncInventoryError(e) raise SyncInventoryError(e)
def getZabbixGroup(self, groups): def setZabbixGroupID(self, groups):
""" """
Returns Zabbix group ID Sets Zabbix group ID as instance variable
INPUT: list of hostgroups INPUT: list of hostgroups
OUTPUT: True / False OUTPUT: True / False
""" """
@ -424,8 +424,8 @@ class NetworkDevice():
""" """
# Check if hostname is already present in Zabbix # Check if hostname is already present in Zabbix
if not self._zabbixHostnameExists(): if not self._zabbixHostnameExists():
# Get group and template ID's for host # Set group and template ID's for host
if not self.getZabbixGroup(groups): if not self.setZabbixGroupID(groups):
e = (f"Unable to find group '{self.hostgroup}' " e = (f"Unable to find group '{self.hostgroup}' "
f"for host {self.name} in Zabbix.") f"for host {self.name} in Zabbix.")
self.logger.warning(e) self.logger.warning(e)
@ -478,20 +478,43 @@ class NetworkDevice():
e = f"Device {self.name}: Unable to add to Zabbix. Host already present." e = f"Device {self.name}: Unable to add to Zabbix. Host already present."
self.logger.warning(e) self.logger.warning(e)
def createZabbixHostgroup(self): def createZabbixHostgroup(self, hostgroups):
""" """
Creates Zabbix host group based on hostgroup format. Creates Zabbix host group based on hostgroup format.
Creates multiple when using a nested format.
""" """
try: final_data = []
groupid = self.zabbix.hostgroup.create(name=self.hostgroup) # Check if the hostgroup is in a nested format and check each parent
e = f"Added hostgroup '{self.hostgroup}'." for pos in range(len(self.hostgroup.split('/'))):
self.logger.info(e) zabbix_hg = self.hostgroup.rsplit('/', pos)[0]
data = {'groupid': groupid["groupids"][0], 'name': self.hostgroup} if self.lookupZabbixHostgroup(hostgroups, zabbix_hg):
return data # Hostgroup already exists
except APIRequestError as e: continue
e = f"Couldn't add hostgroup {self.hostgroup}, Zabbix returned {str(e)}." # Create new group
self.logger.error(e) try:
raise SyncExternalError(e) from e # API call to Zabbix
groupid = self.zabbix.hostgroup.create(name=zabbix_hg)
e = f"Hostgroup '{zabbix_hg}': created in Zabbix."
self.logger.info(e)
# Add group to final data
final_data.append({'groupid': groupid["groupids"][0], 'name': zabbix_hg})
except APIRequestError as e:
e = f"Hostgroup '{zabbix_hg}': unable to create. Zabbix returned {str(e)}."
self.logger.error(e)
raise SyncExternalError(e) from e
return final_data
def lookupZabbixHostgroup(self, group_list, lookup_group):
"""
Function to check if a hostgroup
exists in a list of Zabbix hostgroups
INPUT: Group list and group lookup
OUTPUT: Boolean
"""
for group in group_list:
if group["name"] == lookup_group:
return True
return False
def updateZabbixHost(self, **kwargs): def updateZabbixHost(self, **kwargs):
""" """
@ -513,13 +536,17 @@ class NetworkDevice():
""" """
Checks if Zabbix object is still valid with Netbox parameters. Checks if Zabbix object is still valid with Netbox parameters.
""" """
# Check if the hostgroup exists. # Set Hostgroup ID
# If not, create the hostgroup and try finding the group again # If not, create the hostgroup and try finding the group again
if not self.getZabbixGroup(groups): if not self.setZabbixGroupID(groups):
# No hostgroup was found
if create_hostgroups: if create_hostgroups:
new_group = self.createZabbixHostgroup() # Script is allowed to create a new hostgroup
groups.append(new_group) new_groups = self.createZabbixHostgroup(groups)
self.getZabbixGroup(groups) for group in new_groups:
# Go through all newly created groups
groups.append(group)
self.setZabbixGroupID(groups)
else: else:
e = (f"Device {self.name}: different hostgroup is required but " e = (f"Device {self.name}: different hostgroup is required but "
"unable to create hostgroup without generation permission.") "unable to create hostgroup without generation permission.")

View File

@ -173,16 +173,13 @@ def main(arguments):
create_hostgroups) create_hostgroups)
continue continue
# Add hostgroup is config is set # Add hostgroup is config is set
# and Hostgroup is not present in Zabbix
if create_hostgroups: if create_hostgroups:
for group in zabbix_groups: # Create new hostgroup. Potentially multiple groups if nested
# If hostgroup is already present in Zabbix hostgroups = device.createZabbixHostgroup(zabbix_groups)
if group["name"] == device.hostgroup: # go through all newly created hostgroups
break for group in hostgroups:
else: # Add new hostgroups to zabbix group list
# Create new hostgroup zabbix_groups.append(group)
hostgroup = device.createZabbixHostgroup()
zabbix_groups.append(hostgroup)
# Add device to Zabbix # Add device to Zabbix
device.createInZabbix(zabbix_groups, zabbix_templates, device.createInZabbix(zabbix_groups, zabbix_templates,
zabbix_proxy_list) zabbix_proxy_list)