From 2577f3a786ff6a390c6c2d5ace0a2ced0f1e8d03 Mon Sep 17 00:00:00 2001 From: Arthur Hanson Date: Fri, 2 Dec 2022 05:34:24 -0800 Subject: [PATCH] 11000 improve yaml import (#11075) * 11000 improve yaml import * 11000 add commenting * 11000 add commenting --- netbox/utilities/forms/forms.py | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/netbox/utilities/forms/forms.py b/netbox/utilities/forms/forms.py index af06f219a..bcc598e3c 100644 --- a/netbox/utilities/forms/forms.py +++ b/netbox/utilities/forms/forms.py @@ -217,13 +217,38 @@ class ImportForm(BootstrapMixin, forms.Form): }) def _clean_yaml(self, data): + records = [] try: - return yaml.load_all(data, Loader=yaml.SafeLoader) + for data in yaml.load_all(data, Loader=yaml.SafeLoader): + # checks here are to support both arrays and multiple documents in + # yaml data and return as a consistent list for processing (array): + # - address: 10.0.1.0/24 + # status: active + # - address: 10.0.1.1/24 + # status: active + # vs (multi-document): + # - address: 10.0.1.0/24 + # status: active + # --- + # - address: 10.0.1.1/24 + # status: active + # device_type output uses multi-document format, but array format + # is more common output from other tools. + if type(data) == list: + records.extend(data) + elif type(data) == dict: + records.append(data) + else: + raise forms.ValidationError({ + self.data_field: "Invalid YAML data: data must be dictionaries or lists of dictionaries" + }) except yaml.error.YAMLError as err: raise forms.ValidationError({ self.data_field: f"Invalid YAML data: {err}" }) + return records + class FilterForm(BootstrapMixin, forms.Form): """