update-netbox-tool.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (c) 2017-2023 Joe Clarke <jclarke@cisco.com>
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions
  8. # are met:
  9. # 1. Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. # notice, this list of conditions and the following disclaimer in the
  13. # documentation and/or other materials provided with the distribution.
  14. #
  15. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  16. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  18. # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  19. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  21. # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  22. # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  23. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  24. # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  25. # SUCH DAMAGE.
  26. from __future__ import print_function
  27. from elemental_utils import ElementalNetbox
  28. import requests
  29. from requests.packages.urllib3.exceptions import InsecureRequestWarning # type: ignore
  30. requests.packages.urllib3.disable_warnings(InsecureRequestWarning) # type: ignore
  31. import json
  32. import sys
  33. import re
  34. import os
  35. import argparse
  36. import CLEUCreds # type: ignore
  37. from cleu.config import Config as C # type: ignore
  38. CACHE_FILE = "netbox_tool_cache.json"
  39. SKU_MAP = {
  40. "WS-C3560CX-12PD-S": "WS-C3560CX-12PD-S",
  41. "C9300-48U": "C9300-48P",
  42. "C9300-48P": "C9300-48P",
  43. "C9300-24U": "C9300-24P",
  44. "C9300-24P": "C9300-24P",
  45. "WS-C3750X-24P-S": "WS-C3750X-24P-S",
  46. "WS-C3750X-48P-S": "WS-C3750X-48P-S",
  47. "WS-C3560CG-8": "WS-C3560CG-8PC-S",
  48. "WS-C3560CG-8PC-S": "WS-C3560CG-8PC-S",
  49. "C9500-48Y4C": "C9500-48Y4C",
  50. }
  51. TYPE_OBJ_MAP = {}
  52. INTF_MAP = {"IDF": "loopback0", "Access": "Vlan127"}
  53. INTF_CIDR_MAP = {"IDF": 32, "Access": 24}
  54. SITE_MAP = {"IDF": "IDF Closet", "Access": "Conference Space"}
  55. SITE_OBJ_MAP = {}
  56. ROLE_MAP = {"IDF": "L3 Access Switch", "Access": "L2 Access Switch"}
  57. ROLE_OBJ_MAP = {}
  58. VRF_NAME = "default"
  59. VRF_OBJ = None
  60. TENANT_NAME = "Infrastructure"
  61. TENANT_OBJ = None
  62. def get_devs():
  63. url = f"http://{C.TOOL}/get/switches/json"
  64. devices = []
  65. response = requests.request("GET", url)
  66. code = response.status_code
  67. if code == 200:
  68. j = response.json()
  69. for dev in j:
  70. dev_dic = {}
  71. if dev["IPAddress"] == "0.0.0.0":
  72. continue
  73. # Do not add MDF switches (or APs)
  74. if not re.search(r"^[0-9A-Za-z]{3}-", dev["Hostname"]):
  75. continue
  76. if dev["SKU"] not in SKU_MAP:
  77. continue
  78. dev_dic["type"] = SKU_MAP[dev["SKU"]]
  79. if re.search(r"^[0-9A-Za-z]{3}-[Xx]", dev["Hostname"]):
  80. dev_dic["role"] = ROLE_MAP["IDF"]
  81. dev_dic["intf"] = INTF_MAP["IDF"]
  82. dev_dic["cidr"] = INTF_CIDR_MAP["IDF"]
  83. dev_dic["site"] = SITE_MAP["IDF"]
  84. else:
  85. dev_dic["role"] = ROLE_MAP["Access"]
  86. dev_dic["intf"] = INTF_MAP["Access"]
  87. dev_dic["cidr"] = INTF_CIDR_MAP["Access"]
  88. dev_dic["site"] = SITE_MAP["Access"]
  89. dev_dic["name"] = dev["Hostname"]
  90. dev_dic["aliases"] = [f"{dev['Name']}", f"{dev['AssetTag']}"]
  91. dev_dic["ip"] = dev["IPAddress"]
  92. devices.append(dev_dic)
  93. return devices
  94. def delete_netbox_device(enb: ElementalNetbox, dname: str) -> None:
  95. try:
  96. dev_obj = enb.dcim.devices.get(name=dname)
  97. if dev_obj:
  98. if dev_obj.primary_ip4:
  99. dev_obj.primary_ip4.delete()
  100. dev_obj.delete()
  101. except Exception as e:
  102. sys.stderr.write(f"WARNING: Failed to delete NetBox device for {dname}\n")
  103. def populate_objects(enb: ElementalNetbox) -> None:
  104. global ROLE_OBJ_MAP, SITE_OBJ_MAP, TYPE_OBJ_MAP, TENANT_OBJ, VRF_OBJ
  105. for _, val in ROLE_MAP.items():
  106. ROLE_OBJ_MAP[val] = enb.dcim.device_roles.get(name=val)
  107. for _, val in SITE_MAP.items():
  108. SITE_OBJ_MAP[val] = enb.dcim.sites.get(name=val)
  109. for _, val in SKU_MAP.items():
  110. TYPE_OBJ_MAP[val] = enb.dcim.device_types.get(part_number=val)
  111. TENANT_OBJ = enb.tenancy.tenants.get(name=TENANT_NAME)
  112. VRF_OBJ = enb.ipam.vrfs.get(name=VRF_NAME)
  113. def add_netbox_device(enb: ElementalNetbox, dev: dict) -> None:
  114. role_obj = ROLE_OBJ_MAP[dev["role"]]
  115. type_obj = TYPE_OBJ_MAP[dev["type"]]
  116. tenant_obj = TENANT_OBJ
  117. site_obj = SITE_OBJ_MAP[dev["site"]]
  118. vrf_obj = VRF_OBJ
  119. if not role_obj:
  120. sys.stderr.write(f"ERROR: Invalid role for {dev['name']}: {dev['role']}\n")
  121. return
  122. if not type_obj:
  123. sys.stderr.write(f"ERROR: Invalid type for {dev['name']}: {dev['type']}\n")
  124. return
  125. if not site_obj:
  126. sys.stderr.write(f"ERROR: Invalid site for {dev['name']}: {dev['site']}\n")
  127. return
  128. dev_obj = enb.dcim.devices.create(
  129. name=dev["name"], device_role=role_obj.id, device_type=type_obj.id, site=site_obj.id, tenant=tenant_obj.id
  130. )
  131. if not dev_obj:
  132. sys.stderr.write(f"ERROR: Failed to create NetBox entry for {dev['name']}\n")
  133. return
  134. ip_obj = enb.ipam.ip_addresses.create(address=f"{dev['ip']}/{dev['cidr']}", tenant=tenant_obj.id, vrf=vrf_obj.id)
  135. if not ip_obj:
  136. dev_obj.delete()
  137. sys.stderr.write(f"ERROR: Failed to create IP entry for {dev['ip']}\n")
  138. return
  139. dev_intf = enb.dcim.interfaces.get(device=dev_obj.name, name=dev["intf"])
  140. if not dev_intf:
  141. dev_obj.delete()
  142. ip_obj.delete()
  143. sys.stderr.write(f"ERROR: Failed to find interface {dev['intf']} for {dev['name']}\n")
  144. return
  145. ip_obj.assigned_object_id = dev_intf.id
  146. ip_obj.assigned_object_type = "dcim.interface"
  147. dev["aliases"].sort()
  148. ip_obj.custom_fields["CNAMEs"] = ",".join(dev["aliases"])
  149. ip_obj.save()
  150. dev_obj.primary_ip4 = ip_obj.id
  151. dev_obj.save()
  152. if __name__ == "__main__":
  153. os.environ["NETBOX_ADDRESS"] = C.NETBOX_SERVER
  154. os.environ["NETBOX_API_TOKEN"] = CLEUCreds.NETBOX_API_TOKEN
  155. parser = argparse.ArgumentParser(description="Usage:")
  156. # script arguments
  157. parser.add_argument("--purge", help="Purge previous records", action="store_true")
  158. args = parser.parse_args()
  159. enb = ElementalNetbox()
  160. populate_objects(enb)
  161. prev_records = []
  162. if os.path.exists(CACHE_FILE):
  163. with open(CACHE_FILE) as fd:
  164. prev_records = json.load(fd)
  165. devs = get_devs()
  166. for record in prev_records:
  167. found_record = False
  168. for dev in devs:
  169. hname = dev["name"].replace(f".{C.DNS_DOMAIN}", "")
  170. if record == hname:
  171. found_record = True
  172. break
  173. if found_record:
  174. continue
  175. delete_netbox_device(enb, record)
  176. records = []
  177. for dev in devs:
  178. hname = dev["name"].replace(f".{C.DNS_DOMAIN}", "")
  179. records.append(hname)
  180. if args.purge:
  181. delete_netbox_device(enb, hname)
  182. dev_obj = enb.dcim.devices.get(name=hname)
  183. if not dev_obj:
  184. ip_obj = enb.ipam.ip_addresses.get(address=f"{dev['ip']}/{dev['cidr']}")
  185. cur_entry = None
  186. if ip_obj and ip_obj.assigned_object:
  187. cur_entry = ip_obj.assigned_object.device
  188. if cur_entry:
  189. print(f"INFO: Found old entry for IP {dev['ip']} => {cur_entry.name}")
  190. delete_netbox_device(enb, cur_entry.name)
  191. add_netbox_device(enb, dev)
  192. else:
  193. cur_entry = dev_obj
  194. create_new = True
  195. ip_obj = dev_obj.primary_ip4
  196. if ip_obj and ip_obj.address == f"{dev['ip']}/{dev['cidr']}":
  197. cnames = ip_obj.custom_fields["CNAMEs"]
  198. if not cnames:
  199. cnames = ""
  200. dev["aliases"].sort()
  201. cname_str = ",".join(dev["aliases"])
  202. if cname_str == cnames:
  203. create_new = False
  204. if create_new:
  205. print(f"INFO: Deleting entry for {hname}")
  206. delete_netbox_device(enb, hname)
  207. add_netbox_device(enb, dev)
  208. else:
  209. # print("Not creating a new entry for {} as it already exists".format(dev["name"]))
  210. pass
  211. with open(CACHE_FILE, "w") as fd:
  212. json.dump(records, fd, indent=4)