-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
custom.py
3687 lines (3283 loc) · 129 KB
/
custom.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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# pylint: disable=too-many-lines
import datetime
import json
import os
import os.path
import platform
import ssl
import sys
import threading
import time
import webbrowser
from azext_aks_preview._client_factory import (
CUSTOM_MGMT_AKS_PREVIEW,
cf_agent_pools,
get_compute_client,
)
from azext_aks_preview._consts import (
ADDONS,
ADDONS_DESCRIPTIONS,
CONST_ACC_SGX_QUOTE_HELPER_ENABLED,
CONST_AZURE_KEYVAULT_SECRETS_PROVIDER_ADDON_NAME,
CONST_CONFCOM_ADDON_NAME,
CONST_INGRESS_APPGW_ADDON_NAME,
CONST_INGRESS_APPGW_APPLICATION_GATEWAY_ID,
CONST_INGRESS_APPGW_APPLICATION_GATEWAY_NAME,
CONST_INGRESS_APPGW_SUBNET_CIDR,
CONST_INGRESS_APPGW_SUBNET_ID,
CONST_INGRESS_APPGW_WATCH_NAMESPACE,
CONST_KUBE_DASHBOARD_ADDON_NAME,
CONST_MONITORING_ADDON_NAME,
CONST_MONITORING_LOG_ANALYTICS_WORKSPACE_RESOURCE_ID,
CONST_MONITORING_USING_AAD_MSI_AUTH,
CONST_NODEPOOL_MODE_USER,
CONST_OPEN_SERVICE_MESH_ADDON_NAME,
CONST_ROTATION_POLL_INTERVAL,
CONST_SCALE_DOWN_MODE_DELETE,
CONST_SCALE_SET_PRIORITY_REGULAR,
CONST_SECRET_ROTATION_ENABLED,
CONST_SPOT_EVICTION_POLICY_DELETE,
CONST_VIRTUAL_NODE_ADDON_NAME,
CONST_VIRTUAL_NODE_SUBNET_NAME,
CONST_AZURE_SERVICE_MESH_MODE_ISTIO,
CONST_AZURE_SERVICE_MESH_UPGRADE_COMMAND_START,
CONST_AZURE_SERVICE_MESH_UPGRADE_COMMAND_COMPLETE,
CONST_AZURE_SERVICE_MESH_UPGRADE_COMMAND_ROLLBACK,
CONST_SSH_ACCESS_LOCALUSER,
CONST_NODE_PROVISIONING_STATE_SUCCEEDED,
CONST_DEFAULT_NODE_OS_TYPE,
CONST_VIRTUAL_MACHINE_SCALE_SETS,
CONST_VIRTUAL_MACHINES,
CONST_AVAILABILITY_SET,
CONST_MIN_NODE_IMAGE_VERSION,
CONST_ARTIFACT_SOURCE_DIRECT,
)
from azext_aks_preview._helpers import (
check_is_private_link_cluster,
get_cluster_snapshot_by_snapshot_id,
get_nodepool_snapshot_by_snapshot_id,
print_or_merge_credentials,
process_message_for_run_command,
check_is_monitoring_addon_enabled,
)
from azext_aks_preview._podidentity import (
_ensure_managed_identity_operator_permission,
_ensure_pod_identity_addon_is_enabled,
_fill_defaults_for_pod_identity_profile,
_update_addon_pod_identity,
)
from azext_aks_preview._resourcegroup import get_rg_location
from azext_aks_preview.addonconfiguration import (
add_ingress_appgw_addon_role_assignment,
add_virtual_node_role_assignment,
enable_addons,
)
from azext_aks_preview.aks_diagnostics import aks_kanalyze_cmd, aks_kollect_cmd
from azext_aks_preview.aks_draft.commands import (
aks_draft_cmd_create,
aks_draft_cmd_generate_workflow,
aks_draft_cmd_setup_gh,
aks_draft_cmd_up,
aks_draft_cmd_update,
)
from azext_aks_preview.maintenanceconfiguration import (
aks_maintenanceconfiguration_update_internal,
)
from azure.cli.command_modules.acs._helpers import (
get_user_assigned_identity_by_resource_id
)
from azure.cli.command_modules.acs._validators import (
extract_comma_separated_string,
)
from azure.cli.command_modules.acs.addonconfiguration import (
ensure_container_insights_for_monitoring,
ensure_default_log_analytics_workspace_for_monitoring,
sanitize_loganalytics_ws_resource_id,
)
from azure.cli.core.api import get_config_dir
from azure.cli.core.azclierror import (
ArgumentUsageError,
ClientRequestError,
InvalidArgumentValueError,
MutuallyExclusiveArgumentError,
RequiredArgumentMissingError,
ValidationError,
)
from azure.cli.core.commands import LongRunningOperation
from azure.cli.core.commands.client_factory import get_subscription_id
from azure.cli.core.profiles import ResourceType
from azure.cli.core.util import (
in_cloud_console,
sdk_no_wait,
shell_safe_json_parse,
)
from azure.core.exceptions import (
ResourceNotFoundError,
HttpResponseError,
)
from dateutil.parser import parse
from knack.log import get_logger
from knack.prompting import prompt_y_n
from knack.util import CLIError
from six.moves.urllib.error import URLError
from six.moves.urllib.request import urlopen
logger = get_logger(__name__)
def wait_then_open(url):
"""
Waits for a bit then opens a URL. Useful for waiting for a proxy to come up, and then open the URL.
"""
for _ in range(1, 10):
try:
with urlopen(url, context=_ssl_context()):
break
except URLError:
time.sleep(1)
webbrowser.open_new_tab(url)
def wait_then_open_async(url):
"""
Spawns a thread that waits for a bit then opens a URL.
"""
t = threading.Thread(target=wait_then_open, args=url)
t.daemon = True
t.start()
def _ssl_context():
if sys.version_info < (3, 4) or (in_cloud_console() and platform.system() == 'Windows'):
try:
# added in python 2.7.13 and 3.6
return ssl.SSLContext(ssl.PROTOCOL_TLS)
except AttributeError:
return ssl.SSLContext(ssl.PROTOCOL_TLSv1)
return ssl.create_default_context()
# pylint: disable=too-many-locals
def store_acs_service_principal(subscription_id, client_secret, service_principal,
file_name='acsServicePrincipal.json'):
obj = {}
if client_secret:
obj['client_secret'] = client_secret
if service_principal:
obj['service_principal'] = service_principal
config_path = os.path.join(get_config_dir(), file_name)
full_config = load_service_principals(config_path=config_path)
if not full_config:
full_config = {}
full_config[subscription_id] = obj
with os.fdopen(os.open(config_path, os.O_RDWR | os.O_CREAT | os.O_TRUNC, 0o600),
'w+') as spFile:
json.dump(full_config, spFile)
def load_acs_service_principal(subscription_id, file_name='acsServicePrincipal.json'):
config_path = os.path.join(get_config_dir(), file_name)
config = load_service_principals(config_path)
if not config:
return None
return config.get(subscription_id)
def load_service_principals(config_path):
if not os.path.exists(config_path):
return None
fd = os.open(config_path, os.O_RDONLY)
try:
with os.fdopen(fd) as f:
return shell_safe_json_parse(f.read())
except: # pylint: disable=bare-except
return None
def aks_browse(
cmd,
client,
resource_group_name,
name,
disable_browser=False,
listen_address="127.0.0.1",
listen_port="8001",
):
from azure.cli.command_modules.acs.custom import _aks_browse
return _aks_browse(
cmd,
client,
resource_group_name,
name,
disable_browser,
listen_address,
listen_port,
CUSTOM_MGMT_AKS_PREVIEW,
)
def aks_maintenanceconfiguration_list(
cmd, # pylint: disable=unused-argument
client,
resource_group_name,
cluster_name
):
return client.list_by_managed_cluster(resource_group_name, cluster_name)
def aks_maintenanceconfiguration_show(
cmd, # pylint: disable=unused-argument
client,
resource_group_name,
cluster_name,
config_name
):
logger.warning('resource_group_name: %s, cluster_name: %s, config_name: %s ',
resource_group_name, cluster_name, config_name)
return client.get(resource_group_name, cluster_name, config_name)
def aks_maintenanceconfiguration_delete(
cmd, # pylint: disable=unused-argument
client,
resource_group_name,
cluster_name,
config_name
):
logger.warning('resource_group_name: %s, cluster_name: %s, config_name: %s ',
resource_group_name, cluster_name, config_name)
return client.delete(resource_group_name, cluster_name, config_name)
# pylint: disable=unused-argument
def aks_maintenanceconfiguration_add(
cmd,
client,
resource_group_name,
cluster_name,
config_name,
config_file=None,
weekday=None,
start_hour=None,
schedule_type=None,
interval_days=None,
interval_weeks=None,
interval_months=None,
day_of_week=None,
day_of_month=None,
week_index=None,
duration_hours=None,
utc_offset=None,
start_date=None,
start_time=None
):
configs = client.list_by_managed_cluster(resource_group_name, cluster_name)
for config in configs:
if config.name == config_name:
raise CLIError(
f"Maintenance configuration '{config_name}' already exists, please try a different name, "
"use 'aks maintenanceconfiguration list' to get current list of maitenance configurations"
)
# DO NOT MOVE: get all the original parameters and save them as a dictionary
raw_parameters = locals()
return aks_maintenanceconfiguration_update_internal(cmd, client, raw_parameters)
def aks_maintenanceconfiguration_update(
cmd,
client,
resource_group_name,
cluster_name,
config_name,
config_file=None,
weekday=None,
start_hour=None,
schedule_type=None,
interval_days=None,
interval_weeks=None,
interval_months=None,
day_of_week=None,
day_of_month=None,
week_index=None,
duration_hours=None,
utc_offset=None,
start_date=None,
start_time=None
):
configs = client.list_by_managed_cluster(resource_group_name, cluster_name)
found = False
for config in configs:
if config.name == config_name:
found = True
break
if not found:
raise CLIError(
f"Maintenance configuration '{config_name}' doesn't exist."
"use 'aks maintenanceconfiguration list' to get current list of maitenance configurations"
)
# DO NOT MOVE: get all the original parameters and save them as a dictionary
raw_parameters = locals()
return aks_maintenanceconfiguration_update_internal(cmd, client, raw_parameters)
# pylint: disable=too-many-locals, unused-argument
def aks_create(
cmd,
client,
resource_group_name,
name,
ssh_key_value,
location=None,
kubernetes_version="",
tags=None,
dns_name_prefix=None,
node_osdisk_diskencryptionset_id=None,
disable_local_accounts=False,
disable_rbac=None,
edge_zone=None,
admin_username="azureuser",
generate_ssh_keys=False,
no_ssh_key=False,
pod_cidr=None,
service_cidr=None,
dns_service_ip=None,
docker_bridge_address=None,
load_balancer_sku=None,
load_balancer_managed_outbound_ip_count=None,
load_balancer_outbound_ips=None,
load_balancer_outbound_ip_prefixes=None,
load_balancer_outbound_ports=None,
load_balancer_idle_timeout=None,
load_balancer_backend_pool_type=None,
nat_gateway_managed_outbound_ip_count=None,
nat_gateway_idle_timeout=None,
outbound_type=None,
network_plugin=None,
network_plugin_mode=None,
network_policy=None,
network_dataplane=None,
kube_proxy_config=None,
auto_upgrade_channel=None,
node_os_upgrade_channel=None,
cluster_autoscaler_profile=None,
sku=None,
tier=None,
fqdn_subdomain=None,
api_server_authorized_ip_ranges=None,
enable_private_cluster=False,
private_dns_zone=None,
disable_public_fqdn=False,
service_principal=None,
client_secret=None,
enable_managed_identity=None,
assign_identity=None,
assign_kubelet_identity=None,
enable_aad=False,
enable_azure_rbac=False,
aad_tenant_id=None,
aad_admin_group_object_ids=None,
enable_oidc_issuer=False,
windows_admin_username=None,
windows_admin_password=None,
enable_ahub=False,
enable_windows_gmsa=False,
gmsa_dns_server=None,
gmsa_root_domain_name=None,
attach_acr=None,
skip_subnet_role_assignment=False,
node_resource_group=None,
k8s_support_plan=None,
nrg_lockdown_restriction_level=None,
enable_defender=False,
defender_config=None,
disk_driver_version=None,
disable_disk_driver=False,
disable_file_driver=False,
enable_blob_driver=None,
disable_snapshot_controller=False,
enable_azure_keyvault_kms=False,
azure_keyvault_kms_key_id=None,
azure_keyvault_kms_key_vault_network_access=None,
azure_keyvault_kms_key_vault_resource_id=None,
http_proxy_config=None,
bootstrap_artifact_source=CONST_ARTIFACT_SOURCE_DIRECT,
bootstrap_container_registry_resource_id=None,
# addons
enable_addons=None, # pylint: disable=redefined-outer-name
workspace_resource_id=None,
enable_msi_auth_for_monitoring=True,
enable_syslog=False,
data_collection_settings=None,
ampls_resource_id=None,
enable_high_log_scale_mode=False,
aci_subnet_name=None,
appgw_name=None,
appgw_subnet_cidr=None,
appgw_id=None,
appgw_subnet_id=None,
appgw_watch_namespace=None,
enable_sgxquotehelper=False,
enable_secret_rotation=False,
rotation_poll_interval=None,
enable_app_routing=False,
app_routing_default_nginx_controller=None,
# nodepool paramerters
nodepool_name="nodepool1",
node_vm_size=None,
os_sku=None,
snapshot_id=None,
vnet_subnet_id=None,
pod_subnet_id=None,
pod_ip_allocation_mode=None,
enable_node_public_ip=False,
node_public_ip_prefix_id=None,
enable_cluster_autoscaler=False,
min_count=None,
max_count=None,
node_count=3,
nodepool_tags=None,
nodepool_labels=None,
nodepool_taints=None,
nodepool_initialization_taints=None,
node_osdisk_type=None,
node_osdisk_size=0,
vm_set_type=None,
zones=None,
ppg=None,
max_pods=0,
enable_encryption_at_host=False,
enable_ultra_ssd=False,
enable_fips_image=False,
kubelet_config=None,
linux_os_config=None,
host_group_id=None,
gpu_instance_profile=None,
# misc
yes=False,
no_wait=False,
aks_custom_headers=None,
# extensions
# managed cluster
ip_families=None,
pod_cidrs=None,
service_cidrs=None,
load_balancer_managed_outbound_ipv6_count=None,
enable_pod_security_policy=False,
enable_pod_identity=False,
enable_pod_identity_with_kubenet=False,
enable_workload_identity=False,
enable_image_cleaner=False,
image_cleaner_interval_hours=None,
enable_image_integrity=False,
cluster_snapshot_id=None,
enable_apiserver_vnet_integration=False,
apiserver_subnet_id=None,
dns_zone_resource_id=None,
dns_zone_resource_ids=None,
enable_keda=False,
enable_vpa=False,
enable_addon_autoscaling=False,
enable_cilium_dataplane=False,
custom_ca_trust_certificates=None,
# advanced networking
enable_acns=None,
disable_acns_observability=None,
disable_acns_security=None,
# nodepool
crg_id=None,
message_of_the_day=None,
workload_runtime=None,
enable_custom_ca_trust=False,
nodepool_allowed_host_ports=None,
nodepool_asg_ids=None,
node_public_ip_tags=None,
# safeguards parameters
safeguards_level=None,
safeguards_version=None,
safeguards_excluded_ns=None,
# azure service mesh
enable_azure_service_mesh=None,
revision=None,
# azure monitor profile - metrics
enable_azuremonitormetrics=False,
enable_azure_monitor_metrics=False,
azure_monitor_workspace_resource_id=None,
ksm_metric_labels_allow_list=None,
ksm_metric_annotations_allow_list=None,
grafana_resource_id=None,
enable_windows_recording_rules=False,
# azure monitor profile - app monitoring
enable_azure_monitor_app_monitoring=False,
# metrics profile
enable_cost_analysis=False,
# AI toolchain operator
enable_ai_toolchain_operator=False,
# azure container storage
enable_azure_container_storage=None,
storage_pool_name=None,
storage_pool_size=None,
storage_pool_sku=None,
storage_pool_option=None,
ephemeral_disk_volume_type=None,
ephemeral_disk_nvme_perf_tier=None,
node_provisioning_mode=None,
ssh_access=CONST_SSH_ACCESS_LOCALUSER,
# trusted launch
enable_secure_boot=False,
enable_vtpm=False,
cluster_service_load_balancer_health_probe_mode=None,
if_match=None,
if_none_match=None,
# Static Egress Gateway
enable_static_egress_gateway=False,
# virtualmachines
vm_sizes=None,
# IMDS restriction
enable_imds_restriction=False,
):
# DO NOT MOVE: get all the original parameters and save them as a dictionary
raw_parameters = locals()
# validation for existing cluster
existing_mc = None
try:
existing_mc = client.get(resource_group_name, name)
# pylint: disable=broad-except
except Exception as ex:
logger.debug("failed to get cluster, error: %s", ex)
if existing_mc:
raise ClientRequestError(
f"The cluster '{name}' under resource group '{resource_group_name}' already exists. "
"Please use command 'az aks update' to update the existing cluster, "
"or select a different cluster name to create a new cluster."
)
# decorator pattern
from azure.cli.command_modules.acs._consts import DecoratorEarlyExitException
from azext_aks_preview.managed_cluster_decorator import AKSPreviewManagedClusterCreateDecorator
aks_create_decorator = AKSPreviewManagedClusterCreateDecorator(
cmd=cmd,
client=client,
raw_parameters=raw_parameters,
resource_type=CUSTOM_MGMT_AKS_PREVIEW,
)
try:
# construct mc profile
mc = aks_create_decorator.construct_mc_profile_preview()
except DecoratorEarlyExitException:
# exit gracefully
return None
# send request to create a real managed cluster
return aks_create_decorator.create_mc(mc)
# pylint: disable=too-many-locals, unused-argument
def aks_update(
cmd,
client,
resource_group_name,
name,
tags=None,
disable_local_accounts=False,
enable_local_accounts=False,
load_balancer_managed_outbound_ip_count=None,
load_balancer_outbound_ips=None,
load_balancer_outbound_ip_prefixes=None,
load_balancer_outbound_ports=None,
load_balancer_idle_timeout=None,
load_balancer_backend_pool_type=None,
nat_gateway_managed_outbound_ip_count=None,
nat_gateway_idle_timeout=None,
kube_proxy_config=None,
auto_upgrade_channel=None,
node_os_upgrade_channel=None,
enable_force_upgrade=False,
disable_force_upgrade=False,
upgrade_override_until=None,
cluster_autoscaler_profile=None,
sku=None,
tier=None,
api_server_authorized_ip_ranges=None,
enable_public_fqdn=False,
disable_public_fqdn=False,
enable_managed_identity=False,
assign_identity=None,
assign_kubelet_identity=None,
enable_aad=False,
enable_azure_rbac=False,
disable_azure_rbac=False,
aad_tenant_id=None,
aad_admin_group_object_ids=None,
enable_oidc_issuer=False,
k8s_support_plan=None,
windows_admin_password=None,
enable_ahub=False,
disable_ahub=False,
enable_windows_gmsa=False,
gmsa_dns_server=None,
gmsa_root_domain_name=None,
attach_acr=None,
detach_acr=None,
nrg_lockdown_restriction_level=None,
enable_defender=False,
disable_defender=False,
defender_config=None,
enable_disk_driver=False,
disk_driver_version=None,
disable_disk_driver=False,
enable_file_driver=False,
disable_file_driver=False,
enable_blob_driver=None,
disable_blob_driver=None,
enable_snapshot_controller=False,
disable_snapshot_controller=False,
enable_azure_keyvault_kms=False,
disable_azure_keyvault_kms=False,
azure_keyvault_kms_key_id=None,
azure_keyvault_kms_key_vault_network_access=None,
azure_keyvault_kms_key_vault_resource_id=None,
http_proxy_config=None,
bootstrap_artifact_source=None,
bootstrap_container_registry_resource_id=None,
# addons
enable_secret_rotation=False,
disable_secret_rotation=False,
rotation_poll_interval=None,
# nodepool paramerters
enable_cluster_autoscaler=False,
disable_cluster_autoscaler=False,
update_cluster_autoscaler=False,
min_count=None,
max_count=None,
nodepool_labels=None,
nodepool_taints=None,
nodepool_initialization_taints=None,
# misc
yes=False,
no_wait=False,
aks_custom_headers=None,
# extensions
# managed cluster
ssh_key_value=None,
load_balancer_managed_outbound_ipv6_count=None,
outbound_type=None,
network_plugin=None,
network_plugin_mode=None,
network_policy=None,
network_dataplane=None,
ip_families=None,
pod_cidr=None,
enable_pod_security_policy=False,
disable_pod_security_policy=False,
enable_pod_identity=False,
enable_pod_identity_with_kubenet=False,
disable_pod_identity=False,
enable_workload_identity=False,
disable_workload_identity=False,
enable_image_cleaner=False,
disable_image_cleaner=False,
image_cleaner_interval_hours=None,
enable_image_integrity=False,
disable_image_integrity=False,
enable_apiserver_vnet_integration=False,
apiserver_subnet_id=None,
enable_keda=False,
disable_keda=False,
enable_private_cluster=False,
disable_private_cluster=False,
private_dns_zone=None,
enable_azuremonitormetrics=False,
enable_azure_monitor_metrics=False,
azure_monitor_workspace_resource_id=None,
ksm_metric_labels_allow_list=None,
ksm_metric_annotations_allow_list=None,
grafana_resource_id=None,
enable_windows_recording_rules=False,
disable_azuremonitormetrics=False,
disable_azure_monitor_metrics=False,
# azure monitor profile - app monitoring
enable_azure_monitor_app_monitoring=False,
disable_azure_monitor_app_monitoring=False,
enable_vpa=False,
disable_vpa=False,
enable_addon_autoscaling=False,
disable_addon_autoscaling=False,
cluster_snapshot_id=None,
custom_ca_trust_certificates=None,
# safeguards parameters
safeguards_level=None,
safeguards_version=None,
safeguards_excluded_ns=None,
# advanced networking
enable_acns=None,
disable_acns=None,
disable_acns_observability=None,
disable_acns_security=None,
# metrics profile
enable_cost_analysis=False,
disable_cost_analysis=False,
# AI toolchain operator
enable_ai_toolchain_operator=False,
disable_ai_toolchain_operator=False,
# azure container storage
enable_azure_container_storage=None,
disable_azure_container_storage=None,
storage_pool_name=None,
storage_pool_size=None,
storage_pool_sku=None,
storage_pool_option=None,
azure_container_storage_nodepools=None,
ephemeral_disk_volume_type=None,
ephemeral_disk_nvme_perf_tier=None,
node_provisioning_mode=None,
cluster_service_load_balancer_health_probe_mode=None,
if_match=None,
if_none_match=None,
# Static Egress Gateway
enable_static_egress_gateway=False,
disable_static_egress_gateway=False,
# IMDS restriction
enable_imds_restriction=False,
disable_imds_restriction=False,
):
# DO NOT MOVE: get all the original parameters and save them as a dictionary
raw_parameters = locals()
from azure.cli.command_modules.acs._consts import DecoratorEarlyExitException
from azext_aks_preview.managed_cluster_decorator import AKSPreviewManagedClusterUpdateDecorator
# decorator pattern
aks_update_decorator = AKSPreviewManagedClusterUpdateDecorator(
cmd=cmd,
client=client,
raw_parameters=raw_parameters,
resource_type=CUSTOM_MGMT_AKS_PREVIEW,
)
try:
# update mc profile
mc = aks_update_decorator.update_mc_profile_preview()
except DecoratorEarlyExitException:
# exit gracefully
return None
# send request to update the real managed cluster
return aks_update_decorator.update_mc(mc)
# pylint: disable=unused-argument
def aks_show(cmd, client, resource_group_name, name, aks_custom_headers=None):
headers = get_aks_custom_headers(aks_custom_headers)
mc = client.get(resource_group_name, name, headers=headers)
return _remove_nulls([mc])[0]
# pylint: disable=unused-argument
def aks_stop(cmd, client, resource_group_name, name, no_wait=False):
instance = client.get(resource_group_name, name)
# print warning when stopping a private cluster
if check_is_private_link_cluster(instance):
logger.warning(
"Your private cluster apiserver IP might get changed when it's stopped and started.\n"
"Any user provisioned private endpoints linked to this private cluster will need to be deleted and "
"created again. Any user managed DNS record also needs to be updated with the new IP."
)
return sdk_no_wait(no_wait, client.begin_stop, resource_group_name, name)
# pylint: disable=unused-argument
def aks_list(cmd, client, resource_group_name=None):
if resource_group_name:
managed_clusters = client.list_by_resource_group(resource_group_name)
else:
managed_clusters = client.list()
return _remove_nulls(list(managed_clusters))
def _remove_nulls(managed_clusters):
"""
Remove some often-empty fields from a list of ManagedClusters, so the JSON representation
doesn't contain distracting null fields.
This works around a quirk of the SDK for python behavior. These fields are not sent
by the server, but get recreated by the CLI's own "to_dict" serialization.
"""
attrs = ['tags']
ap_attrs = ['os_disk_size_gb', 'vnet_subnet_id']
sp_attrs = ['secret']
for managed_cluster in managed_clusters:
for attr in attrs:
if getattr(managed_cluster, attr, None) is None:
delattr(managed_cluster, attr)
if managed_cluster.agent_pool_profiles is not None:
for ap_profile in managed_cluster.agent_pool_profiles:
for attr in ap_attrs:
if getattr(ap_profile, attr, None) is None:
delattr(ap_profile, attr)
for attr in sp_attrs:
if getattr(managed_cluster.service_principal_profile, attr, None) is None:
delattr(managed_cluster.service_principal_profile, attr)
return managed_clusters
def aks_get_credentials(
cmd, # pylint: disable=unused-argument
client,
resource_group_name,
name,
admin=False,
user="clusterUser",
path=os.path.join(os.path.expanduser("~"), ".kube", "config"),
overwrite_existing=False,
context_name=None,
public_fqdn=False,
credential_format=None,
aks_custom_headers=None,
):
headers = get_aks_custom_headers(aks_custom_headers)
credentialResults = None
serverType = None
if public_fqdn:
serverType = 'public'
if credential_format:
credential_format = credential_format.lower()
if admin:
raise InvalidArgumentValueError("--format can only be specified when requesting clusterUser credential.")
if admin:
credentialResults = client.list_cluster_admin_credentials(
resource_group_name, name, serverType, headers=headers)
else:
if user.lower() == 'clusteruser':
credentialResults = client.list_cluster_user_credentials(
resource_group_name, name, serverType, credential_format, headers=headers)
elif user.lower() == 'clustermonitoringuser':
credentialResults = client.list_cluster_monitoring_user_credentials(
resource_group_name, name, serverType, headers=headers)
else:
raise InvalidArgumentValueError("The value of option --user is invalid.")
# Check if KUBECONFIG environmental variable is set
# If path is different than default then that means -f/--file is passed
# in which case we ignore the KUBECONFIG variable
# KUBECONFIG can be colon separated. If we find that condition, use the first entry
if "KUBECONFIG" in os.environ and path == os.path.join(os.path.expanduser('~'), '.kube', 'config'):
kubeconfig_path = os.environ["KUBECONFIG"].split(os.pathsep)[0]
if kubeconfig_path:
logger.info("The default path '%s' is replaced by '%s' defined in KUBECONFIG.", path, kubeconfig_path)
path = kubeconfig_path
else:
logger.warning("Invalid path '%s' defined in KUBECONFIG.", kubeconfig_path)
if not credentialResults:
raise CLIError("No Kubernetes credentials found.")
try:
kubeconfig = credentialResults.kubeconfigs[0].value.decode(
encoding='UTF-8')
print_or_merge_credentials(
path, kubeconfig, overwrite_existing, context_name)
except (IndexError, ValueError) as exc:
raise CLIError("Fail to find kubeconfig file.") from exc
def aks_scale(cmd, # pylint: disable=unused-argument
client,
resource_group_name,
name,
node_count,
nodepool_name="",
no_wait=False,
aks_custom_headers=None):
headers = get_aks_custom_headers(aks_custom_headers)
instance = client.get(resource_group_name, name)
_fill_defaults_for_pod_identity_profile(instance.pod_identity_profile)
if len(instance.agent_pool_profiles) > 1 and nodepool_name == "":
raise CLIError(
"There are more than one node pool in the cluster. "
"Please specify nodepool name or use az aks nodepool command to scale node pool"
)
for agent_profile in instance.agent_pool_profiles:
if agent_profile.name == nodepool_name or (nodepool_name == "" and len(instance.agent_pool_profiles) == 1):
if agent_profile.enable_auto_scaling:
raise CLIError(
"Cannot scale cluster autoscaler enabled node pool.")
if agent_profile.type == CONST_VIRTUAL_MACHINES:
if len(agent_profile.virtual_machines_profile.scale.manual) == 1:
agent_profile.virtual_machines_profile.scale.manual[0].count = int(node_count)
else:
raise ClientRequestError("Cannot scale virtual machines node pool with more than one size.")
else:
agent_profile.count = int(node_count)
# null out the SP profile because otherwise validation complains
instance.service_principal_profile = None
return sdk_no_wait(
no_wait,
client.begin_create_or_update,
resource_group_name,
name,
instance,
headers=headers,
)
raise CLIError(f'The nodepool "{nodepool_name}" was not found.')
# pylint: disable=too-many-return-statements, too-many-branches
def aks_upgrade(cmd,
client,
resource_group_name,
name,
kubernetes_version='',
control_plane_only=False,
no_wait=False,
node_image_only=False,
cluster_snapshot_id=None,
aks_custom_headers=None,
enable_force_upgrade=False,
disable_force_upgrade=False,
upgrade_override_until=None,
yes=False,
if_match=None,
if_none_match=None):
msg = 'Kubernetes may be unavailable during cluster upgrades.\n Are you sure you want to perform this operation?'
if not yes and not prompt_y_n(msg, default="n"):
return None
instance = client.get(resource_group_name, name)
_fill_defaults_for_pod_identity_profile(instance.pod_identity_profile)
vmas_cluster = False
for agent_profile in instance.agent_pool_profiles:
if agent_profile.type.lower() == "availabilityset":
vmas_cluster = True
break
if kubernetes_version != '' and node_image_only:
raise CLIError('Conflicting flags. Upgrading the Kubernetes version will also upgrade node image version. '
'If you only want to upgrade the node version please use the "--node-image-only" option only.')
if node_image_only:
msg = "This node image upgrade operation will run across every node pool in the cluster " \
"and might take a while. Do you wish to continue?"
if not yes and not prompt_y_n(msg, default="n"):
return None
# This only provide convenience for customer at client side so they can run az aks upgrade to upgrade all
# nodepools of a cluster. The SDK only support upgrade single nodepool at a time.
for agent_pool_profile in instance.agent_pool_profiles:
if vmas_cluster:
raise CLIError('This cluster is not using VirtualMachineScaleSets. Node image upgrade only operation '
'can only be applied on VirtualMachineScaleSets and VirtualMachines(Preview) cluster.')
agent_pool_client = cf_agent_pools(cmd.cli_ctx)
_upgrade_single_nodepool_image_version(
True, agent_pool_client, resource_group_name, name, agent_pool_profile.name, None)
mc = client.get(resource_group_name, name)
return _remove_nulls([mc])[0]
if cluster_snapshot_id:
CreationData = cmd.get_models(
"CreationData",
resource_type=CUSTOM_MGMT_AKS_PREVIEW,
operation_group="managed_clusters",
)
instance.creation_data = CreationData(
source_resource_id=cluster_snapshot_id
)
mcsnapshot = get_cluster_snapshot_by_snapshot_id(cmd.cli_ctx, cluster_snapshot_id)
kubernetes_version = mcsnapshot.managed_cluster_properties_read_only.kubernetes_version
instance = _update_upgrade_settings(
cmd,