examples.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from django.utils.text import slugify
  2. from dcim.constants import *
  3. from dcim.models import Device, DeviceRole, DeviceType, Site
  4. from extras.scripts import *
  5. class NewBranchScript(Script):
  6. script_name = "New Branch"
  7. script_description = "Provision a new branch site"
  8. script_fields = ['site_name', 'switch_count', 'switch_model']
  9. site_name = StringVar(
  10. description="Name of the new site"
  11. )
  12. switch_count = IntegerVar(
  13. description="Number of access switches to create"
  14. )
  15. switch_model = ObjectVar(
  16. description="Access switch model",
  17. queryset=DeviceType.objects.filter(
  18. manufacturer__name='Cisco',
  19. model__in=['Catalyst 3560X-48T', 'Catalyst 3750X-48T']
  20. )
  21. )
  22. x = BooleanVar(
  23. description="Check me out"
  24. )
  25. def run(self, data):
  26. # Create the new site
  27. site = Site(
  28. name=data['site_name'],
  29. slug=slugify(data['site_name']),
  30. status=SITE_STATUS_PLANNED
  31. )
  32. site.save()
  33. self.log_success("Created new site: {}".format(site))
  34. # Create access switches
  35. switch_role = DeviceRole.objects.get(name='Access Switch')
  36. for i in range(1, data['switch_count'] + 1):
  37. switch = Device(
  38. device_type=data['switch_model'],
  39. name='{}-switch{}'.format(site.slug, i),
  40. site=site,
  41. status=DEVICE_STATUS_PLANNED,
  42. device_role=switch_role
  43. )
  44. switch.save()
  45. self.log_success("Created new switch: {}".format(switch))
  46. # Generate a CSV table of new devices
  47. output = [
  48. 'name,make,model'
  49. ]
  50. for switch in Device.objects.filter(site=site):
  51. attrs = [
  52. switch.name,
  53. switch.device_type.manufacturer.name,
  54. switch.device_type.model
  55. ]
  56. output.append(','.join(attrs))
  57. return '\n'.join(output)