diff --git a/module/netbox/config.py b/module/netbox/config.py index 8f943c0..b4897ea 100644 --- a/module/netbox/config.py +++ b/module/netbox/config.py @@ -128,7 +128,15 @@ def __init__(self): ConfigOption("cache_directory_location", str, description="The location of the directory where the cache files should be stored", - default_value="cache") + default_value="cache"), + + ConfigOption("skip_prune_on_source_failure", + bool, + description="""Safety switch: If any enabled source fails (init/connect/query), + pruning will be skipped for this run to prevent mass orphaning/deletions + during temporary source outages. + """, + default_value=True) ] super().__init__() diff --git a/netbox-sync.py b/netbox-sync.py index e499838..a4e3963 100755 --- a/netbox-sync.py +++ b/netbox-sync.py @@ -124,7 +124,23 @@ def main(): # update data in NetBox nb_handler.update_instance() - # prune orphaned objects from NetBox +# prune orphaned objects from NetBox (safe-guard) +failed_enabled_sources = [ + s for s in inventory.source_list + if getattr(getattr(s, "settings", None), "enabled", False) is True + and getattr(s, "init_successful", False) is False +] + +if nb_handler.settings.prune_enabled and \ + getattr(nb_handler.settings, "skip_prune_on_source_failure", True) and \ + len(failed_enabled_sources) > 0: + + failed_names = ", ".join([getattr(s, "name", "") for s in failed_enabled_sources]) + log.warning( + f"Skipping prune because {len(failed_enabled_sources)} enabled source(s) failed init: {failed_names}" + ) + +else: nb_handler.prune_data() # delete tags which are not used anymore diff --git a/settings-example.ini b/settings-example.ini index 432d4c2..ab3a91f 100644 --- a/settings-example.ini +++ b/settings-example.ini @@ -109,6 +109,9 @@ host_fqdn = netbox.example.com ;;; a sources name. Sources can be defined multiple times to represent different sources. ;;; +; Safety: If any enabled source fails, skip pruning for this run +;skip_prune_on_source_failure = True + [source/my-vcenter-example] ; Defines if this source is enabled or not