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.

46 lines
1.3 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 VMs')
  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 VMs... (ctrl+c to cancel)')
  25. time.sleep(PAUSE_SECONDS)
  26. conn = openstack.connect()
  27. for server in conn.compute.servers():
  28. created_at = datetime.datetime.strptime(server.created_at, DATE_FORMAT)
  29. if created_at < oldest_allowed:
  30. print('Will delete server %(name)s' % server)
  31. if not args.dry_run:
  32. conn.compute.delete_server(server)
  33. if __name__ == '__main__':
  34. # execute only if run as a script
  35. main()