Skip to content

Instantly share code, notes, and snippets.

@sean-smith
Created September 14, 2019 06:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sean-smith/fa95262d4c032aa8dfc48aca07e61f3d to your computer and use it in GitHub Desktop.
Save sean-smith/fa95262d4c032aa8dfc48aca07e61f3d to your computer and use it in GitHub Desktop.
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