2021-02-08 11:59:33 +01:00
|
|
|
import sys
|
|
|
|
|
2021-02-08 10:35:31 +01:00
|
|
|
from django.contrib.contenttypes.models import ContentType
|
|
|
|
from extras.models import Webhook
|
2022-04-05 08:34:08 +02:00
|
|
|
from startup_script_utils import load_yaml, split_params
|
2021-02-08 10:35:31 +01:00
|
|
|
|
2021-02-08 11:59:33 +01:00
|
|
|
webhooks = load_yaml("/opt/netbox/initializers/webhooks.yml")
|
2021-02-08 10:35:31 +01:00
|
|
|
|
|
|
|
if webhooks is None:
|
2021-02-08 11:59:33 +01:00
|
|
|
sys.exit()
|
2021-02-08 10:35:31 +01:00
|
|
|
|
|
|
|
|
|
|
|
def get_content_type_id(hook_name, content_type):
|
2021-02-08 11:59:33 +01:00
|
|
|
try:
|
|
|
|
return ContentType.objects.get(model=content_type).id
|
|
|
|
except ContentType.DoesNotExist as ex:
|
|
|
|
print("⚠️ Webhook '{0}': The object_type '{1}' is unknown.".format(hook_name, content_type))
|
|
|
|
raise ex
|
2021-02-08 10:35:31 +01:00
|
|
|
|
|
|
|
|
|
|
|
for hook in webhooks:
|
2021-02-08 11:59:33 +01:00
|
|
|
obj_types = hook.pop("object_types")
|
2021-02-08 10:35:31 +01:00
|
|
|
|
2021-02-08 11:59:33 +01:00
|
|
|
try:
|
|
|
|
obj_type_ids = [get_content_type_id(hook["name"], obj) for obj in obj_types]
|
|
|
|
except ContentType.DoesNotExist:
|
|
|
|
continue
|
2021-02-08 10:35:31 +01:00
|
|
|
|
2022-04-05 08:34:08 +02:00
|
|
|
matching_params, defaults = split_params(hook)
|
|
|
|
webhook, created = Webhook.objects.get_or_create(**matching_params, defaults=defaults)
|
|
|
|
|
2021-02-08 11:59:33 +01:00
|
|
|
if created:
|
|
|
|
webhook.content_types.set(obj_type_ids)
|
|
|
|
webhook.save()
|
2021-02-08 10:35:31 +01:00
|
|
|
|
2021-02-08 11:59:33 +01:00
|
|
|
print("🪝 Created Webhook {0}".format(webhook.name))
|