|
| 1 | +"""Diffsync adapter class for Nautobot.""" |
| 2 | +# pylint: disable=import-error,no-name-in-module |
| 3 | +import os |
| 4 | +import requests |
| 5 | +from models import RegionModel, SiteModel |
| 6 | +from diffsync import DiffSync |
| 7 | + |
| 8 | + |
| 9 | +NAUTOBOT_URL = os.getenv("NAUTOBOT_URL", "https://demo.nautobot.com") |
| 10 | +NAUTOBOT_TOKEN = os.getenv("NAUTOBOT_TOKEN", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") |
| 11 | + |
| 12 | + |
| 13 | +class RegionNautobotModel(RegionModel): |
| 14 | + """Implementation of Region create/update/delete methods for updating remote Nautobot data.""" |
| 15 | + |
| 16 | + @classmethod |
| 17 | + def create(cls, diffsync, ids, attrs): |
| 18 | + """Create a new Region record in remote Nautobot. |
| 19 | +
|
| 20 | + Args: |
| 21 | + diffsync (NautobotRemote): DiffSync adapter owning this Region |
| 22 | + ids (dict): Initial values for this model's _identifiers |
| 23 | + attrs (dict): Initial values for this model's _attributes |
| 24 | + """ |
| 25 | + data = { |
| 26 | + "name": ids["name"], |
| 27 | + "slug": attrs["slug"], |
| 28 | + } |
| 29 | + if attrs["description"]: |
| 30 | + data["description"] = attrs["description"] |
| 31 | + if attrs["parent_name"]: |
| 32 | + data["parent"] = str(diffsync.get(diffsync.region, attrs["parent_name"]).pk) |
| 33 | + diffsync.post("/api/dcim/regions/", data) |
| 34 | + return super().create(diffsync, ids=ids, attrs=attrs) |
| 35 | + |
| 36 | + def update(self, attrs): |
| 37 | + """Update an existing Region record in remote Nautobot. |
| 38 | +
|
| 39 | + Args: |
| 40 | + attrs (dict): Updated values for this record's _attributes |
| 41 | + """ |
| 42 | + data = {} |
| 43 | + if "slug" in attrs: |
| 44 | + data["slug"] = attrs["slug"] |
| 45 | + if "description" in attrs: |
| 46 | + data["description"] = attrs["description"] |
| 47 | + if "parent_name" in attrs: |
| 48 | + if attrs["parent_name"]: |
| 49 | + data["parent"] = str(self.get(self.region, attrs["parent_name"]).pk) |
| 50 | + else: |
| 51 | + data["parent"] = None |
| 52 | + self.diffsync.patch(f"/api/dcim/regions/{self.pk}/", data) |
| 53 | + return super().update(attrs) |
| 54 | + |
| 55 | + def delete(self): # pylint: disable= useless-super-delegation |
| 56 | + """Delete an existing Region record from remote Nautobot.""" |
| 57 | + # self.diffsync.delete(f"/api/dcim/regions/{self.pk}/") |
| 58 | + return super().delete() |
| 59 | + |
| 60 | + |
| 61 | +class SiteNautobotModel(SiteModel): |
| 62 | + """Implementation of Site create/update/delete methods for updating remote Nautobot data.""" |
| 63 | + |
| 64 | + @classmethod |
| 65 | + def create(cls, diffsync, ids, attrs): |
| 66 | + """Create a new Site in remote Nautobot. |
| 67 | +
|
| 68 | + Args: |
| 69 | + diffsync (NautobotRemote): DiffSync adapter owning this Site |
| 70 | + ids (dict): Initial values for this model's _identifiers |
| 71 | + attrs (dict): Initial values for this model's _attributes |
| 72 | + """ |
| 73 | + diffsync.post( |
| 74 | + "/api/dcim/sites/", |
| 75 | + { |
| 76 | + "name": ids["name"], |
| 77 | + "slug": attrs["slug"], |
| 78 | + "description": attrs["description"], |
| 79 | + "status": attrs["status_slug"], |
| 80 | + "region": {"name": attrs["region_name"]} if attrs["region_name"] else None, |
| 81 | + "latitude": attrs["latitude"], |
| 82 | + "longitude": attrs["longitude"], |
| 83 | + }, |
| 84 | + ) |
| 85 | + return super().create(diffsync, ids=ids, attrs=attrs) |
| 86 | + |
| 87 | + def update(self, attrs): |
| 88 | + """Update an existing Site record in remote Nautobot. |
| 89 | +
|
| 90 | + Args: |
| 91 | + attrs (dict): Updated values for this record's _attributes |
| 92 | + """ |
| 93 | + data = {} |
| 94 | + if "slug" in attrs: |
| 95 | + data["slug"] = attrs["slug"] |
| 96 | + if "description" in attrs: |
| 97 | + data["description"] = attrs["description"] |
| 98 | + if "status_slug" in attrs: |
| 99 | + data["status"] = attrs["status_slug"] |
| 100 | + if "region_name" in attrs: |
| 101 | + if attrs["region_name"]: |
| 102 | + data["region"] = {"name": attrs["region_name"]} |
| 103 | + else: |
| 104 | + data["region"] = None |
| 105 | + if "latitude" in attrs: |
| 106 | + data["latitude"] = attrs["latitude"] |
| 107 | + if "longitude" in attrs: |
| 108 | + data["longitude"] = attrs["longitude"] |
| 109 | + self.diffsync.patch(f"/api/dcim/sites/{self.pk}/", data) |
| 110 | + return super().update(attrs) |
| 111 | + |
| 112 | + def delete(self): # pylint: disable= useless-super-delegation |
| 113 | + """Delete an existing Site record from remote Nautobot.""" |
| 114 | + # self.diffsync.delete(f"/api/dcim/sites/{self.pk}/") |
| 115 | + return super().delete() |
| 116 | + |
| 117 | + |
| 118 | +class NautobotRemote(DiffSync): |
| 119 | + """DiffSync adapter class for loading data from a remote Nautobot instance using Python requests.""" |
| 120 | + |
| 121 | + # Model classes used by this adapter class |
| 122 | + region = RegionNautobotModel |
| 123 | + site = SiteNautobotModel |
| 124 | + |
| 125 | + # Top-level class labels, i.e. those classes that are handled directly rather than as children of other models |
| 126 | + top_level = ("region", "site") |
| 127 | + |
| 128 | + def __init__(self, *args, url=NAUTOBOT_URL, token=NAUTOBOT_TOKEN, **kwargs): |
| 129 | + """Instantiate this class, but do not load data immediately from the remote system. |
| 130 | +
|
| 131 | + Args: |
| 132 | + url (str): URL of the remote Nautobot system |
| 133 | + token (str): REST API authentication token |
| 134 | + job (Job): The running Job instance that owns this DiffSync adapter instance |
| 135 | + """ |
| 136 | + super().__init__(*args, **kwargs) |
| 137 | + if not url or not token: |
| 138 | + raise ValueError("Both url and token must be specified!") |
| 139 | + self.url = url |
| 140 | + self.token = token |
| 141 | + self.headers = { |
| 142 | + "Accept": "application/json", |
| 143 | + "Authorization": f"Token {self.token}", |
| 144 | + } |
| 145 | + |
| 146 | + def load(self): |
| 147 | + """Load Region and Site data from the remote Nautobot instance.""" |
| 148 | + region_data = requests.get(f"{self.url}/api/dcim/regions/", headers=self.headers, params={"limit": 0}).json() |
| 149 | + regions = region_data["results"] |
| 150 | + while region_data["next"]: |
| 151 | + region_data = requests.get(region_data["next"], headers=self.headers, params={"limit": 0}).json() |
| 152 | + regions.extend(region_data["results"]) |
| 153 | + |
| 154 | + for region_entry in regions: |
| 155 | + region = self.region( |
| 156 | + name=region_entry["name"], |
| 157 | + slug=region_entry["slug"], |
| 158 | + description=region_entry["description"] or None, |
| 159 | + parent_name=region_entry["parent"]["name"] if region_entry["parent"] else None, |
| 160 | + pk=region_entry["id"], |
| 161 | + ) |
| 162 | + self.add(region) |
| 163 | + |
| 164 | + site_data = requests.get(f"{self.url}/api/dcim/sites/", headers=self.headers, params={"limit": 0}).json() |
| 165 | + sites = site_data["results"] |
| 166 | + while site_data["next"]: |
| 167 | + site_data = requests.get(site_data["next"], headers=self.headers, params={"limit": 0}).json() |
| 168 | + sites.extend(site_data["results"]) |
| 169 | + |
| 170 | + for site_entry in sites: |
| 171 | + site = self.site( |
| 172 | + name=site_entry["name"], |
| 173 | + slug=site_entry["slug"], |
| 174 | + status_slug=site_entry["status"]["value"] if site_entry["status"] else "active", |
| 175 | + region_name=site_entry["region"]["name"] if site_entry["region"] else None, |
| 176 | + description=site_entry["description"], |
| 177 | + longitude=site_entry["longitude"], |
| 178 | + latitude=site_entry["latitude"], |
| 179 | + pk=site_entry["id"], |
| 180 | + ) |
| 181 | + self.add(site) |
| 182 | + |
| 183 | + def post(self, path, data): |
| 184 | + """Send an appropriately constructed HTTP POST request.""" |
| 185 | + response = requests.post(f"{self.url}{path}", headers=self.headers, json=data) |
| 186 | + response.raise_for_status() |
| 187 | + return response |
| 188 | + |
| 189 | + def patch(self, path, data): |
| 190 | + """Send an appropriately constructed HTTP PATCH request.""" |
| 191 | + response = requests.patch(f"{self.url}{path}", headers=self.headers, json=data) |
| 192 | + response.raise_for_status() |
| 193 | + return response |
| 194 | + |
| 195 | + def delete(self, path): |
| 196 | + """Send an appropriately constructed HTTP DELETE request.""" |
| 197 | + response = requests.delete(f"{self.url}{path}", headers=self.headers) |
| 198 | + response.raise_for_status() |
| 199 | + return response |
0 commit comments