Skip to content

Instantly share code, notes, and snippets.

@decoupca
Created September 20, 2022 20:48
Show Gist options
  • Save decoupca/139b77b2fe55e879d015c8ddc3e53058 to your computer and use it in GitHub Desktop.
Save decoupca/139b77b2fe55e879d015c8ddc3e53058 to your computer and use it in GitHub Desktop.
NetBox custom validator for requiring a primary IPv4 when device set to active or staged
from extras.validators import CustomValidator
import re
class PrimaryIP4Validation(CustomValidator):
"""Require primary IPv4 value when status is set to active or staged"""
def validate(self, device):
# only these roles will enforce a primary IP when set to active.
# implicitly excludes non-network devices like patch panels and storage drawers.
required_ip_roles = [
"firewall",
"load-balancer",
"router",
"switch",
"voice-gateway",
"wan-accelerator",
"wireless-controller",
]
needs_ip = device.device_role.slug in required_ip_roles
# secondary stack members' hostnames end in -U#, where # is the stack number
# these devices do not need an IP, since only the stack master has one.
stack_member = re.match(r"^.*-U\d+$", device.name)
if (
needs_ip
and (device.status == "active" or device.status == "staged")
and not device.primary_ip4
and not stack_member
):
self.fail(
'Primary IPv4 address must be set when status is "active" or "staged".'
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment