The command loaded the zone with Zone.objects.get(...) and then tested
the result for truthiness:
nb_zone = Zone.objects.get(...)
if nb_zone:
...export...
else:
self.stderr.write('Zone not found in Netbox. Aborting')
Zone.objects.get() either returns a model instance (always truthy) or
raises Zone.DoesNotExist. It never returns a falsy value, so the else
branch was unreachable dead code. A missing zone is already handled
correctly: DoesNotExist is a subclass of Exception, which the
surrounding try/except catches and converts into a CommandError.
Drop the dead if/else and call export_bind_zone_file directly.
47 lines
1.5 KiB
Python
47 lines
1.5 KiB
Python
import netbox_dns.models
|
|
from netbox_dns_bridge.utils import export_bind_zone_file
|
|
from django.core.management.base import BaseCommand, CommandError
|
|
|
|
|
|
class Command(BaseCommand):
|
|
|
|
def add_arguments(self, parser):
|
|
parser.add_argument(
|
|
"--view",
|
|
type=str,
|
|
help="The name of the view the Zone to be exported is in",
|
|
)
|
|
parser.add_argument(
|
|
"--zone", type=str, help="The FQDN of the Zone to be exported"
|
|
)
|
|
parser.add_argument(
|
|
"--file", type=str, help="Path of the zone file to be written"
|
|
)
|
|
|
|
def handle(self, *args, **options):
|
|
# Load parameters
|
|
view_name = options["view"]
|
|
zone_name = options["zone"]
|
|
file_path = options["file"]
|
|
|
|
if not view_name:
|
|
raise CommandError("No --view parameter given")
|
|
elif not zone_name:
|
|
raise CommandError("No --zone parameter given")
|
|
elif not file_path:
|
|
raise CommandError("No --file parameter given")
|
|
|
|
try:
|
|
# Load the zone from NetBox DNS
|
|
nb_zone = netbox_dns.models.Zone.objects.get(
|
|
view__name=view_name, name=zone_name
|
|
)
|
|
|
|
export_bind_zone_file(nb_zone, file_path=file_path)
|
|
self.stdout.write(
|
|
self.style.SUCCESS(f"Zone '{zone_name}' exported to '{file_path}'")
|
|
)
|
|
|
|
except Exception as e:
|
|
raise CommandError(f"Failed to export zone: {e}")
|