8 DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
11 log = logging.getLogger('openstack-cleanup')
13 parser = argparse.ArgumentParser(description='Cleanup OpenStack resources')
15 parser.add_argument('-v', '--verbose', action='store_true',
16 help='Increase verbosity')
17 parser.add_argument('--hours', type=int, default=4,
18 help='Age (in hours) of VMs to cleanup (default: 4h)')
19 parser.add_argument('--dry-run', action='store_true',
20 help='Do not delete anything')
22 args = parser.parse_args()
24 oldest_allowed = datetime.datetime.now() - datetime.timedelta(hours=args.hours)
29 print('Running in dry-run mode')
31 print('This will delete resources... (ctrl+c to cancel)')
32 time.sleep(PAUSE_SECONDS)
34 conn = openstack.connect()
37 map_if_old(conn.compute.delete_server,
38 conn.compute.servers())
40 print('Security groups...')
41 map_if_old(conn.network.delete_security_group,
42 conn.network.security_groups())
46 map_if_old(conn.network.delete_port,
48 except openstack.exceptions.ConflictException as ex:
49 # Need to find subnet-id which should be removed from a router
50 for sn in conn.network.subnets():
52 fn_if_old(conn.network.delete_subnet, sn)
53 except openstack.exceptions.ConflictException:
54 for r in conn.network.routers():
55 print("Deleting subnet %s from router %s", sn, r)
57 conn.network.remove_interface_from_router(
59 except Exception as ex:
60 print("Failed to delete subnet from router as %s", ex)
62 # After removing unnecessary subnet from router, retry to delete ports
63 map_if_old(conn.network.delete_port,
67 map_if_old(conn.network.delete_subnet,
68 conn.network.subnets())
71 for n in conn.network.networks():
72 if not n.is_router_external:
73 fn_if_old(conn.network.delete_network, n)
76 # runs the given fn to all elements of the that are older than allowed
77 def map_if_old(fn, items):
82 # run the given fn function only if the passed item is older than allowed
83 def fn_if_old(fn, item):
84 created_at = datetime.datetime.strptime(item.created_at, DATE_FORMAT)
85 if item.name == "default": # skip default security group
87 if created_at < oldest_allowed:
88 print('Will delete %(name)s (%(id)s)' % item)
93 if __name__ == '__main__':
94 # execute only if run as a script