-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathadd_cluster.py
106 lines (85 loc) · 3.3 KB
/
add_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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import json
import boto3
from util import validate_config_input, validate_unique_cluster_name
import storage
SECRETS_CLIENT = boto3.client('secretsmanager')
def add_cluster(event, context):
"""Add cluster and initial credentials.
Handler function for lambda (entry point)"""
validate_config_input(event['body'])
cluster_config = json.loads(event['body'])
cluster_users = cluster_config['users']
cluster_table = storage.get_cluster_table()
for cluster in get_clusters(cluster_config):
try:
cluster_name = cluster['name']
cluster_server = cluster['cluster']['server']
cluster_authority = cluster['cluster'].get(
'certificate-authority-data', 'NA')
except KeyError as err:
print(f'Invalid cluster config: {err}')
raise err
# Put into dynamodb cluster info
if validate_unique_cluster_name(cluster_name, cluster_table) is None:
names = [user['name'] for user in get_users(cluster_config)]
for name in get_users(cluster_config):
for user_data, secret in name['user'].items():
save_creds(cluster_name, name['name'], user_data, secret)
update_cluster_users_secret_name(
cluster_name, name['name'], user_data, cluster_users)
cluster_table.put_item(
Item={
'id': cluster_name,
'server': cluster_server,
'certificate-authority-data': cluster_authority,
'users': [names],
'users_config': cluster_users
}
)
return {
"statusCode": 200,
"body": json.dumps(
{"message": f'Cluster and config added {cluster_name}'}
),
}
return {
"statusCode": 404,
"body": json.dumps(
{"message": f'Cluster {cluster_name} already exists'}
)
}
def get_users(cluster_config):
"""Get users from config object"""
return list(cluster_config['users'])
def save_creds(cluster_name, name, user_data, secret):
"""Save creds for users in config object"""
print(f'Saving {name}-{user_data}-{cluster_name} secret...')
SECRETS_CLIENT.create_secret(
Name=f'hyper-kube-config-{name}-{user_data}-{cluster_name}',
SecretString=secret,
Tags=[
{
'Key': 'cluster_name',
'Value': cluster_name
},
{
'Key': 'name',
'Value': name
},
{
'Key': 'user_data',
'Value': user_data
}
]
)
def get_clusters(cluster_config):
"""Get list of clusters"""
return list(cluster_config['clusters'])
def update_cluster_users_secret_name(cluster_name, name,
user_data, cluster_users):
"""Update secret data with AWS Secret Manager reference name"""
print(f'HERE is cluster_users: {cluster_users}')
for user in cluster_users:
if user['name'] == name and user_data in user['user']:
val = f'hyper-kube-config-{name}-{user_data}-{cluster_name}'
user['user'][user_data] = val