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