Created
April 10, 2024 18:35
-
-
Save jsenecal/4175aa6fec46cb7a74ab43fcaaf3ec19 to your computer and use it in GitHub Desktop.
Netbox revert_changes.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from extras.scripts import Script, StringVar | |
from utilities.exceptions import AbortScript | |
from extras.models import ObjectChange | |
from dcim.models import Site | |
class revert_change(Script): | |
class Meta: | |
name = "Revert Change" | |
description = "Revert a change made to an object" | |
request_id = StringVar(label="Request ID", description="The request ID of the change to revert", required=True) | |
def run(self, data, commit): | |
request_id = data['request_id'] | |
changes = ObjectChange.objects.filter(request_id=request_id) | |
if not changes: | |
self.log_failure(f"No changes found with request ID {request_id}") | |
for change in changes: | |
if change.action != "update": | |
raise AbortScript(f"Change with request ID {request_id} is not an update") | |
if not change.changed_object: | |
raise AbortScript(f"Change with request ID {request_id} has no changed object") | |
if change.changed_object_type.name != 'prefix': | |
raise AbortScript(f"Change with request ID {request_id} is not a prefix change") | |
old_site_id = change.prechange_data.get('site') | |
changed_prefix = change.changed_object | |
if changed_prefix.pk and hasattr(changed_prefix, 'snapshot'): | |
changed_prefix.snapshot() | |
# Check if old_site_id is not None before reverting | |
if old_site_id is not None: | |
changed_prefix.site = Site.objects.get(id=old_site_id) | |
else: | |
# Handle the case where the original state had no site associated | |
# This may involve setting the site to None or other appropriate actions | |
changed_prefix.site = None | |
changed_prefix.full_clean() | |
changed_prefix.save() | |
self.log_success( | |
f"Reverted changelog [{change}]({change.get_absolute_url()}) on prefix [{changed_prefix}]({changed_prefix.get_absolute_url()})" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment