-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathauto-efs-setup.py
604 lines (435 loc) · 16.8 KB
/
auto-efs-setup.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
import argparse
import boto3
import subprocess
import string
import random
import yaml
import urllib.request
from shutil import which
from time import sleep
def main():
header()
verify_prerequisites()
setup_iam_authorization()
setup_efs_driver()
setup_efs_file_system()
# setup_efs_provisioning()
footer()
def header():
print("=================================================================")
print(" EFS Setup")
def verify_prerequisites():
print("=================================================================")
print(" Prerequisites Verification")
print("=================================================================")
verify_oidc_provider_prerequisite()
verify_eksctl_is_installed()
verify_kubectl_is_installed()
def verify_oidc_provider_prerequisite():
print("Verifying OIDC provider...")
if is_oidc_provider_present():
print("OIDC provider found")
else:
raise Exception(f"Prerequisite not met : No OIDC provider found for cluster '{CLUSTER_NAME}'!")
def is_oidc_provider_present() -> bool:
iam_client = get_iam_client()
oidc_providers = iam_client.list_open_id_connect_providers()["OpenIDConnectProviderList"]
if len(oidc_providers) == 0:
return False
for oidc_provider in oidc_providers:
oidc_provider_tags = iam_client.get_open_id_connect_provider(
OpenIDConnectProviderArn=oidc_provider["Arn"]
)["Tags"]
if any(tag["Key"] == "alpha.eksctl.io/cluster-name" and \
tag["Value"] == CLUSTER_NAME \
for tag in oidc_provider_tags):
return True
return False
def get_iam_client():
return boto3.client(
"iam",
region_name=CLUSTER_REGION
)
def verify_eksctl_is_installed():
print("Verifying eksctl is installed...")
is_prerequisite_met = which("eksctl") is not None
if is_prerequisite_met:
print("eksctl found!")
else:
raise Exception("Prerequisite not met : eksctl could not be found, make sure it is installed or in your PATH!")
def verify_kubectl_is_installed():
print("Verifying kubectl is installed...")
is_prerequisite_met = which("kubectl") is not None
if is_prerequisite_met:
print("kubectl found!")
else:
raise Exception("Prerequisite not met : kubectl could not be found, make sure it is installed or in your PATH!")
def setup_iam_authorization():
print("=================================================================")
print(" IAM Authorization Setup")
print("=================================================================")
setup_efs_iam_policy()
setup_efs_iam_service_account()
def setup_efs_iam_policy():
if does_need_to_create_efs_iam_policy():
create_efs_iam_policy()
else:
print(f"Skipping EFS IAM policy creation, '{EFS_IAM_POLICY_NAME}' already exists!")
def does_need_to_create_efs_iam_policy():
iam_resource = get_iam_resource()
try:
iam_resource.Policy(EFS_IAM_POLICY_ARN).load()
return False
except iam_resource.meta.client.exceptions.NoSuchEntityException:
return True
def get_iam_resource():
return boto3.resource(
"iam",
region_name=CLUSTER_REGION
)
def create_efs_iam_policy():
print("Creating EFS IAM policy...")
policy_document = get_efs_iam_policy_document()
iam_client = get_iam_client()
iam_client.create_policy(
PolicyName=EFS_IAM_POLICY_NAME,
PolicyDocument=policy_document,
Description="EFS CSI Driver Policy"
)
print("EFS IAM policy created!")
def get_efs_iam_policy_document():
url = "https://raw.githubusercontent.com/kubernetes-sigs/aws-efs-csi-driver/v1.3.6/docs/iam-policy-example.json"
response = urllib.request.urlopen(url)
data = response.read()
return data.decode('utf-8')
def setup_efs_iam_service_account():
create_efs_iam_service_account()
def create_efs_iam_service_account():
print("Creating EFS IAM service account...")
subprocess.run([
"eksctl",
"create",
"iamserviceaccount",
"--name",
"efs-csi-controller-sa",
"--namespace",
"kube-system",
"--cluster",
CLUSTER_NAME,
"--attach-policy-arn",
EFS_IAM_POLICY_ARN,
"--approve",
"--override-existing-serviceaccounts",
"--region",
CLUSTER_REGION
])
print("EFS IAM service account created!")
def setup_efs_driver():
print("=================================================================")
print(" EFS Driver Setup")
print("=================================================================")
install_efs_driver()
def install_efs_driver():
print("Installing EFS driver...")
kubectl_kustomize_apply("https://github.com/kubernetes-sigs/aws-efs-csi-driver/deploy/kubernetes/overlays/stable/?ref=tags/v1.3.6")
print("EFS driver installed!")
def kubectl_kustomize_apply(file_name: str):
subprocess.run([
"kubectl",
"apply",
"-k",
file_name
])
def kubectl_apply(file_name: str):
subprocess.run([
"kubectl",
"apply",
"-f",
file_name
])
def setup_efs_file_system():
print("=================================================================")
print(" EFS File System Setup")
print("=================================================================")
if does_need_to_create_efs_file_system():
if does_need_to_create_efs_security_group():
create_efs_security_group()
else:
print(f"Skipping EFS security group creation, security group '{EFS_SECURITY_GROUP_NAME}' already exists!")
create_efs_file_system()
else:
print(f"Skipping EFS file system creation, file system '{EFS_FILE_SYSTEM_NAME}' already exists!")
def does_need_to_create_efs_file_system() -> bool:
efs_client = get_efs_client()
efs_file_systems = efs_client.describe_file_systems()["FileSystems"]
return not any(file_system.get("Name", "") == EFS_FILE_SYSTEM_NAME for file_system in efs_file_systems)
def get_efs_client():
return boto3.client(
"efs",
region_name=CLUSTER_REGION
)
def does_need_to_create_efs_security_group() -> bool:
ec2_client = get_ec2_client()
efs_security_groups_with_matching_name = ec2_client.describe_security_groups(
Filters=[
{
"Name": "group-name",
"Values": [
EFS_SECURITY_GROUP_NAME
]
}
]
)["SecurityGroups"]
return len(efs_security_groups_with_matching_name) == 0
def get_ec2_client():
return boto3.client(
"ec2",
region_name=CLUSTER_REGION
)
def create_efs_security_group():
print(f"Creating security group '{EFS_SECURITY_GROUP_NAME}'...")
eks_client = get_eks_client()
ec2_client = get_ec2_client()
cluster_info = get_cluster_info(eks_client)
vpc_id = get_vpc_id(cluster_info)
cidr_block_ip = get_cidr_block_ip(ec2_client, vpc_id)
security_group_id = create_security_group_resource(ec2_client, vpc_id)
authorize_security_group_ingress(cidr_block_ip, ec2_client, security_group_id)
print("Security group created!")
def get_eks_client():
return boto3.client(
"eks",
region_name=CLUSTER_REGION
)
def get_cluster_info(eks_client):
return eks_client.describe_cluster(
name=CLUSTER_NAME
)["cluster"]
def get_vpc_id(cluster_info):
return cluster_info["resourcesVpcConfig"]["vpcId"]
def get_cidr_block_ip(ec2_client, vpc_id):
return ec2_client.describe_vpcs(
Filters=[
{
"Name": "tag:alpha.eksctl.io/cluster-name",
"Values": [CLUSTER_NAME]
},
],
VpcIds=[vpc_id]
)["Vpcs"][0]["CidrBlock"]
def create_security_group_resource(ec2_client, vpc_id):
return ec2_client.create_security_group(
Description="Kubeflow EFS security group",
GroupName=EFS_SECURITY_GROUP_NAME,
VpcId=vpc_id,
)["GroupId"]
def authorize_security_group_ingress(cidr_block_ip, ec2_client, security_group_id):
tcp_port = 2049
ec2_client.authorize_security_group_ingress(
CidrIp=cidr_block_ip,
FromPort=tcp_port,
ToPort=tcp_port,
GroupId=security_group_id,
IpProtocol="tcp",
)
def create_efs_file_system():
print("Creating EFS file system...")
efs_client = get_efs_client()
efs_file_system_creation_token = generate_creation_token()
efs_client.create_file_system(
CreationToken=efs_file_system_creation_token,
PerformanceMode=EFS_FILE_SYSTEM_PERFORMANCE_MODE,
Encrypted=True,
ThroughputMode=EFS_FILE_SYSTEM_THROUGHPUT_MODE,
Backup=False,
Tags=[
{
"Key": "Name",
"Value": EFS_FILE_SYSTEM_NAME
},
]
)
print("EFS file system created!")
wait_for_efs_file_system_to_become_available(efs_file_system_creation_token)
create_efs_mount_targets(efs_file_system_creation_token)
def generate_creation_token(size=64, chars=string.ascii_uppercase) -> str:
return ''.join(random.choice(chars) for _ in range(size))
def wait_for_efs_file_system_to_become_available(efs_file_system_creation_token):
efs_client = get_efs_client()
status = None
print("Waiting for EFS file system to become available...")
while status != "available":
status = efs_client.describe_file_systems(
CreationToken=efs_file_system_creation_token
)["FileSystems"][0]["LifeCycleState"]
if status == "error":
raise Exception("An unexpected error occurred while waiting for the EFS file system to become available!")
sleep(1)
print("EFS file system is available!")
def create_efs_mount_targets(efs_file_system_creation_token):
efs_client = get_efs_client()
file_system_id = get_file_system_id_from_creation_token(efs_client, efs_file_system_creation_token)
ec2_client = get_ec2_client()
efs_security_group_id = get_efs_security_group_id(ec2_client)
subnet_ids = get_cluster_public_subnet_ids(ec2_client)
mount_target_ids = create_mount_targets(efs_client, efs_security_group_id, file_system_id, subnet_ids)
wait_for_mount_target_to_become_available(efs_client, mount_target_ids)
def get_file_system_id_from_creation_token(efs_client, efs_file_system_creation_token):
return efs_client.describe_file_systems(
CreationToken=efs_file_system_creation_token
)["FileSystems"][0]["FileSystemId"]
def get_efs_security_group_id(ec2_client):
return ec2_client.describe_security_groups(
Filters=[
{
"Name": "group-name",
"Values": [
EFS_SECURITY_GROUP_NAME
]
}
]
)["SecurityGroups"][0]["GroupId"]
def get_cluster_public_subnet_ids(ec2_client):
subnets = ec2_client.describe_subnets(
Filters=[
{
"Name": "tag:alpha.eksctl.io/cluster-name",
"Values": [CLUSTER_NAME]
},
{
"Name": "tag:aws:cloudformation:logical-id",
"Values": ["SubnetPublic*"]
},
]
)["Subnets"]
def get_subnet_id(subnet):
return subnet["SubnetId"]
return list(map(get_subnet_id, subnets))
def create_mount_targets(efs_client, efs_security_group_id, file_system_id, subnet_ids):
mount_target_ids = []
for subnet_id in subnet_ids:
print(f"Creating mount target in subnet {subnet_id}...")
mount_target_id = efs_client.create_mount_target(
FileSystemId=file_system_id,
SubnetId=subnet_id,
SecurityGroups=[efs_security_group_id]
)["MountTargetId"]
print(f"Mount target {mount_target_id} created!")
mount_target_ids.append(mount_target_id)
return mount_target_ids
def wait_for_mount_target_to_become_available(efs_client, mount_target_ids):
for mount_target_id in mount_target_ids:
status = None
print(f"Waiting for EFS mount target {mount_target_id} to become available...")
while status != "available":
status = efs_client.describe_mount_targets(
MountTargetId=mount_target_id
)["MountTargets"][0]["LifeCycleState"]
if status == "error":
raise Exception(f"An unexpected error occurred while waiting for the mount target {mount_target_id}!")
sleep(1)
print(f"{mount_target_id} mount target is available!")
def setup_efs_provisioning():
print("=================================================================")
print(" EFS Provisioning Setup")
print("=================================================================")
setup_dynamic_provisioning()
def setup_dynamic_provisioning():
print("Setting up dynamic provisioning...")
update_dynamic_provisioning_storage_class_file()
apply_dynamic_provisioning_storage_class()
print("Dynamic provisioning setup done!")
def update_dynamic_provisioning_storage_class_file():
efs_client = get_efs_client()
file_system_id = get_file_system_id_from_name(efs_client)
storage_class_file_yaml_content = read_dynamic_provisioning_storage_class_file_content()
edit_dynamic_provisioning_storage_class_fields(
file_system_id,
storage_class_file_yaml_content
)
def read_dynamic_provisioning_storage_class_file_content():
with open(EFS_DYNAMIC_PROVISIONING_STORAGE_CLASS_FILE_PATH, "r") as file:
storage_class_file_content = file.read()
return yaml.safe_load(storage_class_file_content)
def edit_dynamic_provisioning_storage_class_fields(
file_system_id,
storage_class_file_yaml_content
):
print("Editing storage class with appropriate values...")
storage_class_file_yaml_content["parameters"]["fileSystemId"] = file_system_id
with open(EFS_DYNAMIC_PROVISIONING_STORAGE_CLASS_FILE_PATH, "w") as file:
file.write(yaml.dump(storage_class_file_yaml_content))
def get_file_system_id_from_name(efs_client):
def name_matches(filesystem):
return filesystem["Name"] == EFS_FILE_SYSTEM_NAME
file_systems = efs_client.describe_file_systems()["FileSystems"]
file_system = next(filter(name_matches, file_systems))
return file_system["FileSystemId"]
def apply_dynamic_provisioning_storage_class():
print("Creating storage class...")
kubectl_apply(EFS_DYNAMIC_PROVISIONING_STORAGE_CLASS_FILE_PATH)
print("Storage class created!")
def footer():
print("=================================================================")
print(" EFS Setup Complete")
print("=================================================================")
parser = argparse.ArgumentParser()
parser.add_argument(
'--region',
type=str,
metavar="CLUSTER_REGION",
help='Your cluster region code (eg: us-east-2)',
required=True
)
parser.add_argument(
'--cluster',
type=str,
metavar="CLUSTER_NAME",
help='Your cluster name (eg: mycluster-1)',
required=True
)
EFS_FILE_SYSTEM_NAME_DEFAULT = "KubeflowEfs"
parser.add_argument(
'--efs_file_system_name',
type=str,
default=EFS_FILE_SYSTEM_NAME_DEFAULT,
help=f"Default is set to {EFS_FILE_SYSTEM_NAME_DEFAULT}",
required=False
)
EFS_SECURITY_GROUP_NAME_DEFAULT = "KubeflowEfsSecurityGroup"
parser.add_argument(
'--efs_security_group_name',
type=str,
default=EFS_SECURITY_GROUP_NAME_DEFAULT,
help=f"Default is set to {EFS_SECURITY_GROUP_NAME_DEFAULT}",
required=False
)
EFS_PERFORMANCE_MODE_DEFAULT = "generalPurpose"
parser.add_argument(
'--efs_performance_mode',
type=str,
default=EFS_PERFORMANCE_MODE_DEFAULT,
help=f"Default is set to {EFS_PERFORMANCE_MODE_DEFAULT}",
required=False
)
EFS_THROUGHPUT_MODE_DEFAULT = "bursting"
parser.add_argument(
'--efs_throughput_mode',
type=str,
default=EFS_THROUGHPUT_MODE_DEFAULT,
help=f"Default is set to {EFS_THROUGHPUT_MODE_DEFAULT}",
required=False
)
args, _ = parser.parse_known_args()
if __name__ == "__main__":
CLUSTER_REGION = args.region
CLUSTER_NAME = args.cluster
EFS_FILE_SYSTEM_NAME = args.efs_file_system_name
EFS_SECURITY_GROUP_NAME = args.efs_security_group_name
EFS_FILE_SYSTEM_PERFORMANCE_MODE = args.efs_performance_mode
EFS_FILE_SYSTEM_THROUGHPUT_MODE = args.efs_throughput_mode
AWS_ACCOUNT_ID = boto3.client('sts').get_caller_identity()["Account"]
EFS_IAM_POLICY_NAME = "AmazonEKS_EFS_CSI_Driver_Policy"
EFS_IAM_POLICY_ARN = f"arn:aws:iam::{AWS_ACCOUNT_ID}:policy/{EFS_IAM_POLICY_NAME}"
EFS_DYNAMIC_PROVISIONING_STORAGE_CLASS_FILE_PATH = "sc.yaml"
main()