From 2ea3a51ff4d482338a9731158234df2a844d2109 Mon Sep 17 00:00:00 2001 From: Lukasz Polanski Date: Thu, 16 Nov 2023 16:20:15 +0200 Subject: [PATCH] Closes #13808: render-config API endpoint for virtual machines --- netbox/virtualization/api/views.py | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/netbox/virtualization/api/views.py b/netbox/virtualization/api/views.py index 5b9cf411733..cc64b1f6fe0 100644 --- a/netbox/virtualization/api/views.py +++ b/netbox/virtualization/api/views.py @@ -1,8 +1,12 @@ +from rest_framework.decorators import action +from rest_framework.renderers import JSONRenderer +from rest_framework.response import Response from rest_framework.routers import APIRootView from dcim.models import Device -from extras.api.mixins import ConfigContextQuerySetMixin +from extras.api.mixins import ConfigContextQuerySetMixin, ConfigTemplateRenderMixin from netbox.api.viewsets import NetBoxModelViewSet +from netbox.api.renderers import TextRenderer from utilities.utils import count_related from virtualization import filtersets from virtualization.models import Cluster, ClusterGroup, ClusterType, VirtualMachine, VMInterface @@ -52,7 +56,7 @@ class ClusterViewSet(NetBoxModelViewSet): # Virtual machines # -class VirtualMachineViewSet(ConfigContextQuerySetMixin, NetBoxModelViewSet): +class VirtualMachineViewSet(ConfigContextQuerySetMixin, NetBoxModelViewSet, ConfigTemplateRenderMixin): queryset = VirtualMachine.objects.prefetch_related( 'site', 'cluster', 'device', 'role', 'tenant', 'platform', 'primary_ip4', 'primary_ip6', 'tags' ) @@ -78,6 +82,23 @@ def get_serializer_class(self): return serializers.VirtualMachineWithConfigContextSerializer + @action(detail=True, methods=['post'], url_path='render-config', renderer_classes=[JSONRenderer, TextRenderer]) + def render_config(self, request, pk): + """ + Resolve and render the preferred ConfigTemplate for this virtual machine. + """ + vm = self.get_object() + configtemplate = vm.get_config_template() + if not configtemplate: + return Response({'error': 'No config template found for this virtualmachine.'}, status=HTTP_400_BAD_REQUEST) + + # Compile context data + context_data = vm.get_config_context() + context_data.update(request.data) + context_data.update({'virtualmachine': vm}) + + return self.render_configtemplate(request, configtemplate, context_data) + class VMInterfaceViewSet(NetBoxModelViewSet): queryset = VMInterface.objects.prefetch_related(