-
Notifications
You must be signed in to change notification settings - Fork 8
/
remove_cluster.py
74 lines (60 loc) · 2.21 KB
/
remove_cluster.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import json
import boto3
from util import validate_config_input, validate_unique_cluster_name
import storage
SECRETS_CLIENT = boto3.client('secretsmanager')
def remove_cluster(event, context):
"""Remove cluster and all associated credentials"""
"""{ "cluster_name": "foo-prod-cluster.com" }"""
CLUSTER_TABLE = storage.get_cluster_table()
validate_config_input(event['body'])
post_body = json.loads(event['body'])
cluster_name = post_body['cluster_name']
if validate_unique_cluster_name(cluster_name, CLUSTER_TABLE) is not None:
# Remove associated user secrets
delete_secrets(cluster_name)
# Remove cluster
CLUSTER_TABLE.delete_item(
Key={
'id': cluster_name
}
)
return {
"statusCode": 200,
"body": json.dumps(
{"message": (f'Cluster and associated secrets '
f'removed for: {cluster_name}')}
),
}
return {
"statusCode": 404,
"body": json.dumps(
{"message": f'Cluster {cluster_name} does not exist'}
)
}
def delete_secrets(cluster_name):
"""Delete AWS Secrets Manager secrets"""
resp = SECRETS_CLIENT.list_secrets()
secrets = []
while resp:
secrets += resp['SecretList']
nextToken = resp.get('NextToken')
if nextToken is not None:
resp = SECRETS_CLIENT.list_secrets(NextToken=nextToken)
else:
resp = None
for secret in secrets:
if 'Tags' in secret:
for tag in secret['Tags']:
if (tag['Key'] == 'cluster_name'
and tag['Value'] == cluster_name):
try:
print(f"Deleting secret: {secret['Name']}")
SECRETS_CLIENT.delete_secret(
SecretId=f"{secret['Name']}",
ForceDeleteWithoutRecovery=True
)
except Exception as err:
# XXX - handle correct exceptions here!
print((f"Secret {secret} not found, "
f"nothing to delete: {err}"))