You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.1 KiB

  1. #!/usr/bin/env python
  2. import argparse
  3. import openstack
  4. import logging
  5. import datetime
  6. import time
  7. DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
  8. PAUSE_SECONDS = 5
  9. log = logging.getLogger('openstack-cleanup')
  10. parser = argparse.ArgumentParser(description='Cleanup OpenStack resources')
  11. parser.add_argument('-v', '--verbose', action='store_true',
  12. help='Increase verbosity')
  13. parser.add_argument('--hours', type=int, default=4,
  14. help='Age (in hours) of VMs to cleanup (default: 4h)')
  15. parser.add_argument('--dry-run', action='store_true',
  16. help='Do not delete anything')
  17. args = parser.parse_args()
  18. oldest_allowed = datetime.datetime.now() - datetime.timedelta(hours=args.hours)
  19. def main():
  20. if args.dry_run:
  21. print('Running in dry-run mode')
  22. else:
  23. print('This will delete resources... (ctrl+c to cancel)')
  24. time.sleep(PAUSE_SECONDS)
  25. conn = openstack.connect()
  26. print('Servers...')
  27. map_if_old(conn.compute.delete_server,
  28. conn.compute.servers())
  29. print('Security groups...')
  30. map_if_old(conn.network.delete_security_group,
  31. conn.network.security_groups())
  32. print('Ports...')
  33. map_if_old(conn.network.delete_port,
  34. conn.network.ports())
  35. print('Subnets...')
  36. map_if_old(conn.network.delete_subnet,
  37. conn.network.subnets())
  38. print('Networks...')
  39. for n in conn.network.networks():
  40. if not n.is_router_external:
  41. fn_if_old(conn.network.delete_network, n)
  42. # runs the given fn to all elements of the that are older than allowed
  43. def map_if_old(fn, items):
  44. for item in items:
  45. fn_if_old(fn, item)
  46. # run the given fn function only if the passed item is older than allowed
  47. def fn_if_old(fn, item):
  48. created_at = datetime.datetime.strptime(item.created_at, DATE_FORMAT)
  49. if item.name == "default": # skip default security group
  50. return
  51. if created_at < oldest_allowed:
  52. print('Will delete %(name)s (%(id)s)' % item)
  53. if not args.dry_run:
  54. fn(item)
  55. if __name__ == '__main__':
  56. # execute only if run as a script
  57. main()