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.

78 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. 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('Servers...')
  28. map_if_old(conn.compute.delete_server,
  29. conn.compute.servers())
  30. print('Security groups...')
  31. map_if_old(conn.network.delete_security_group,
  32. conn.network.security_groups())
  33. print('Ports...')
  34. map_if_old(conn.network.delete_port,
  35. conn.network.ports())
  36. print('Subnets...')
  37. map_if_old(conn.network.delete_subnet,
  38. conn.network.subnets())
  39. print('Networks...')
  40. for n in conn.network.networks():
  41. if not n.is_router_external:
  42. fn_if_old(conn.network.delete_network, n)
  43. # runs the given fn to all elements of the that are older than allowed
  44. def map_if_old(fn, items):
  45. for item in items:
  46. fn_if_old(fn, item)
  47. # run the given fn function only if the passed item is older than allowed
  48. def fn_if_old(fn, item):
  49. created_at = datetime.datetime.strptime(item.created_at, DATE_FORMAT)
  50. if item.name == "default": # skip default security group
  51. return
  52. if created_at < oldest_allowed:
  53. print('Will delete %(name)s (%(id)s)' % item)
  54. if not args.dry_run:
  55. fn(item)
  56. if __name__ == '__main__':
  57. # execute only if run as a script
  58. main()