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.

74 lines
2.0 KiB

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