|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +""" |
| 4 | +Delete infrastructure for a cluster without using Terraform. Useful for CI clusters. |
| 5 | +
|
| 6 | +Usage: |
| 7 | + delete-cluster.py PREFIX |
| 8 | +
|
| 9 | +Where PREFIX is the string at the start of the resource's names. |
| 10 | +It will list matching resources and prompt to confirm deletion. |
| 11 | +""" |
| 12 | + |
| 13 | +import sys, json, subprocess, pprint |
| 14 | + |
| 15 | + |
| 16 | +CLUSTER_RESOURCES = ['server', 'port', 'volume'] |
| 17 | + |
| 18 | +def delete_cluster(cluster_prefix): |
| 19 | + to_delete = {} |
| 20 | + for resource_type in CLUSTER_RESOURCES: |
| 21 | + to_delete[resource_type] = [] |
| 22 | + resource_list = subprocess.run(f'openstack {resource_type} list --format json', stdout=subprocess.PIPE, shell=True) |
| 23 | + resources = json.loads(resource_list.stdout) |
| 24 | + for item in resources: |
| 25 | + try: |
| 26 | + if item['Name'] is not None and item['Name'].startswith(cluster_prefix): |
| 27 | + print(resource_type, item['Name'], item['ID']) |
| 28 | + to_delete[resource_type].append(item) |
| 29 | + except: |
| 30 | + print(resource_type, item) |
| 31 | + raise |
| 32 | + if input('Delete these (y/n)?:') == 'y': |
| 33 | + for resource_type in CLUSTER_RESOURCES: |
| 34 | + items = [v['ID'] for v in to_delete[resource_type]] |
| 35 | + if items: |
| 36 | + # delete all resources of each type in a single call for speed: |
| 37 | + subprocess.run(f"openstack {resource_type} delete {' '.join(items)}", stdout=subprocess.PIPE, shell=True) |
| 38 | + print(f'Deleted {len(items)} {resource_type}s') |
| 39 | + else: |
| 40 | + print('Cancelled - no resources deleted') |
| 41 | + |
| 42 | +if __name__ == '__main__': |
| 43 | + if len(sys.argv) != 2: |
| 44 | + print('ERROR: Incorrect argument(s).\n' + __doc__) |
| 45 | + exit(1) |
| 46 | + delete_cluster(sys.argv[1]) |
0 commit comments