update-netbox-tool.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. }
  48. TYPE_OBJ_MAP = {}
  49. INTF_MAP = {"IDF": "loopback0", "Access": "Vlan127"}
  50. INTF_CIDR_MAP = {"IDF": 32, "Access": 24}
  51. SITE_MAP = {"IDF": "IDF Closet", "Access": "Conference Space"}
  52. SITE_OBJ_MAP = {}
  53. ROLE_MAP = {"IDF": "L3 Access Switch", "Access": "L2 Access Switch"}
  54. ROLE_OBJ_MAP = {}
  55. VRF_NAME = "default"
  56. VRF_OBJ = None
  57. TENANT_NAME = "Infrastructure"
  58. TENANT_OBJ = None
  59. def get_devs():
  60. url = f"http://{C.TOOL}/get/switches/json"
  61. devices = []
  62. response = requests.request("GET", url)
  63. code = response.status_code
  64. if code == 200:
  65. j = response.json()
  66. for dev in j:
  67. dev_dic = {}
  68. if dev["IPAddress"] == "0.0.0.0":
  69. continue
  70. # Do not add MDF switches (or APs)
  71. if not re.search(r"^[0-9A-Za-z]{3}-", dev["Hostname"]):
  72. continue
  73. if dev["SKU"] not in SKU_MAP:
  74. continue
  75. dev_dic["type"] = SKU_MAP[dev["SKU"]]
  76. if re.search(r"^[0-9A-Za-z]{3}-[Xx]", dev["Hostname"]):
  77. dev_dic["role"] = ROLE_MAP["IDF"]
  78. dev_dic["intf"] = INTF_MAP["IDF"]
  79. dev_dic["cidr"] = INTF_CIDR_MAP["IDF"]
  80. dev_dic["site"] = SITE_MAP["IDF"]
  81. else:
  82. dev_dic["role"] = ROLE_MAP["Access"]
  83. dev_dic["intf"] = INTF_MAP["Access"]
  84. dev_dic["cidr"] = INTF_CIDR_MAP["Access"]
  85. dev_dic["site"] = SITE_MAP["Access"]
  86. dev_dic["name"] = dev["Hostname"]
  87. dev_dic["aliases"] = [f"{dev['Name']}", f"{dev['AssetTag']}"]
  88. dev_dic["ip"] = dev["IPAddress"]
  89. devices.append(dev_dic)
  90. return devices
  91. def delete_netbox_device(enb: ElementalNetbox, dname: str) -> None:
  92. try:
  93. dev_obj = enb.dcim.devices.get(name=dname)
  94. if dev_obj:
  95. if dev_obj.primary_ip4:
  96. dev_obj.primary_ip4.delete()
  97. dev_obj.delete()
  98. except Exception as e:
  99. sys.stderr.write(f"WARNING: Failed to delete NetBox device for {dname}\n")
  100. def populate_objects(enb: ElementalNetbox) -> None:
  101. global ROLE_OBJ_MAP, SITE_OBJ_MAP, TYPE_OBJ_MAP, TENANT_OBJ, VRF_OBJ
  102. for _, val in ROLE_MAP.items():
  103. ROLE_OBJ_MAP[val] = enb.dcim.device_roles.get(name=val)
  104. for _, val in SITE_MAP.items():
  105. SITE_OBJ_MAP[val] = enb.dcim.sites.get(name=val)
  106. for _, val in SKU_MAP.items():
  107. TYPE_OBJ_MAP[val] = enb.dcim.device_types.get(part_number=val)
  108. TENANT_OBJ = enb.tenancy.tenants.get(name=TENANT_NAME)
  109. VRF_OBJ = enb.ipam.vrfs.get(name=VRF_NAME)
  110. def add_netbox_device(enb: ElementalNetbox, dev: dict) -> None:
  111. role_obj = ROLE_OBJ_MAP[dev["role"]]
  112. type_obj = TYPE_OBJ_MAP[dev["type"]]
  113. tenant_obj = TENANT_OBJ
  114. site_obj = SITE_OBJ_MAP[dev["site"]]
  115. vrf_obj = VRF_OBJ
  116. if not role_obj:
  117. sys.stderr.write(f"ERROR: Invalid role for {dev['name']}: {dev['role']}\n")
  118. return
  119. if not type_obj:
  120. sys.stderr.write(f"ERROR: Invalid type for {dev['name']}: {dev['type']}\n")
  121. return
  122. if not site_obj:
  123. sys.stderr.write(f"ERROR: Invalid site for {dev['name']}: {dev['site']}\n")
  124. return
  125. dev_obj = enb.dcim.devices.create(
  126. name=dev["name"], device_role=role_obj.id, device_type=type_obj.id, site=site_obj.id, tenant=tenant_obj.id
  127. )
  128. if not dev_obj:
  129. sys.stderr.write(f"ERROR: Failed to create NetBox entry for {dev['name']}\n")
  130. return
  131. ip_obj = enb.ipam.ip_addresses.create(address=f"{dev['ip']}/{dev['cidr']}", tenant=tenant_obj.id, vrf=vrf_obj.id)
  132. if not ip_obj:
  133. dev_obj.delete()
  134. sys.stderr.write(f"ERROR: Failed to create IP entry for {dev['ip']}\n")
  135. return
  136. dev_intf = enb.dcim.interfaces.get(device=dev_obj.name, name=dev["intf"])
  137. if not dev_intf:
  138. dev_obj.delete()
  139. ip_obj.delete()
  140. sys.stderr.write(f"ERROR: Failed to find interface {dev['intf']} for {dev['name']}\n")
  141. return
  142. ip_obj.assigned_object_id = dev_intf.id
  143. ip_obj.assigned_object_type = "dcim.interface"
  144. dev["aliases"].sort()
  145. ip_obj.custom_fields["CNAMEs"] = ",".join(dev["aliases"])
  146. ip_obj.save()
  147. dev_obj.primary_ip4 = ip_obj.id
  148. dev_obj.save()
  149. if __name__ == "__main__":
  150. os.environ["NETBOX_ADDRESS"] = C.NETBOX_SERVER
  151. os.environ["NETBOX_API_TOKEN"] = CLEUCreds.NETBOX_API_TOKEN
  152. parser = argparse.ArgumentParser(description="Usage:")
  153. # script arguments
  154. parser.add_argument("--purge", help="Purge previous records", action="store_true")
  155. args = parser.parse_args()
  156. enb = ElementalNetbox()
  157. populate_objects(enb)
  158. prev_records = []
  159. if os.path.exists(CACHE_FILE):
  160. with open(CACHE_FILE) as fd:
  161. prev_records = json.load(fd)
  162. devs = get_devs()
  163. for record in prev_records:
  164. found_record = False
  165. for dev in devs:
  166. hname = dev["name"].replace(f".{C.DNS_DOMAIN}", "")
  167. if record == hname:
  168. found_record = True
  169. break
  170. if found_record:
  171. continue
  172. delete_netbox_device(enb, record)
  173. records = []
  174. for dev in devs:
  175. hname = dev["name"].replace(f".{C.DNS_DOMAIN}", "")
  176. records.append(hname)
  177. if args.purge:
  178. delete_netbox_device(enb, hname)
  179. dev_obj = enb.dcim.devices.get(name=hname)
  180. if not dev_obj:
  181. ip_obj = enb.ipam.ip_addresses.get(address=f"{dev['ip']}/{dev['cidr']}")
  182. cur_entry = None
  183. if ip_obj and ip_obj.assigned_object:
  184. cur_entry = ip_obj.assigned_object.device
  185. if cur_entry:
  186. print(f"INFO: Found old entry for IP {dev['ip']} => {cur_entry.name}")
  187. delete_netbox_device(enb, cur_entry.name)
  188. add_netbox_device(enb, dev)
  189. else:
  190. cur_entry = dev_obj
  191. create_new = True
  192. ip_obj = dev_obj.primary_ip4
  193. if ip_obj:
  194. cnames = ip_obj.custom_fields["CNAMEs"]
  195. if not cnames:
  196. cnames = ""
  197. dev["aliases"].sort()
  198. cname_str = ",".join(dev["aliases"])
  199. if cname_str == cnames:
  200. create_new = False
  201. if create_new:
  202. print(f"INFO: Deleting entry for {hname}")
  203. delete_netbox_device(enb, hname)
  204. add_netbox_device(enb, dev)
  205. else:
  206. # print("Not creating a new entry for {} as it already exists".format(dev["name"]))
  207. pass
  208. with open(CACHE_FILE, "w") as fd:
  209. json.dump(records, fd, indent=4)