Created
September 14, 2019 06:37
-
-
Save sean-smith/be54a29b3bc30c9a271feec4fcf9e0f4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import boto3 | |
class ClusterDestroyer: | |
"""Destroy all ParallelCluster clusters in a given region.""" | |
def __init__(self, region, dryrun): | |
self.__created_clusters = [] | |
self.region = region | |
self.dryrun = dryrun | |
self.cfn_client = self.__init_cfn_client() | |
def __init_cfn_client(self): | |
return boto3.client("cloudformation", region_name=self.region) | |
def destroy_cluster(self, name): | |
"""Destroy a created cluster.""" | |
try: | |
self.cfn_client.delete_stack(StackName=name) | |
except Exception as e: | |
raise e | |
def destroy_all_clusters(self): | |
"""Destroy all created clusters.""" | |
print("Destroying all clusters") | |
self.__created_clusters = self.list_all_clusters() | |
for cluster in self.__created_clusters: | |
try: | |
print("Destroying {0}".format(cluster)) | |
if not self.dryrun: | |
self.destroy_cluster(cluster) | |
except Exception as e: | |
print("Failed when destroying cluster {0} with exception {1}.".format(key, e)) | |
def list_all_clusters(self): | |
"""List all parallelcluster clusters""" | |
cfn = boto3.client("cloudformation", region_name=self.region) | |
clusters = [] | |
try: | |
stacks = cfn.describe_stacks().get("Stacks") | |
for stack in stacks: | |
if stack.get("ParentId") is None and stack.get("StackName").startswith("parallelcluster-"): | |
clusters.append(stack.get("StackName")) | |
except ClientError as e: | |
raise e | |
return clusters | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser(description="Get AWS ParallelCluster Clusters and delete them") | |
parser.add_argument("--region", type=str, help="aws region", required=True) | |
parser.add_argument( | |
"--dryrun", | |
action="store_true", | |
help="If set, clusters to be deleted will only be listed", | |
default=False, | |
required=False, | |
) | |
args = parser.parse_args() | |
factory = ClusterDestroyer(args.region, args.dryrun) | |
factory.destroy_all_clusters() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment