-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
custom.py
2467 lines (2016 loc) · 134 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.
# --------------------------------------------------------------------------------------------
from argparse import Namespace
import errno
import logging
from logging import exception
import os
import json
import tempfile
import time
import subprocess
from subprocess import Popen, PIPE, run, STDOUT, call, DEVNULL
from base64 import b64encode, b64decode
import stat
import platform
from xml.dom.pulldom import default_bufsize
from azure.core.exceptions import ClientAuthenticationError
import yaml
import urllib.request
import shutil
from _thread import interrupt_main
from psutil import process_iter, NoSuchProcess, AccessDenied, ZombieProcess, net_connections
from azure.cli.core import get_default_cli
from knack.util import CLIError
from knack.log import get_logger
from knack.prompting import prompt_y_n
from knack.prompting import NoTTYException
from azure.cli.core.commands.client_factory import get_subscription_id
from azure.cli.core.commands import LongRunningOperation
from azure.cli.core._profile import Profile
from azure.cli.core.util import sdk_no_wait
from azure.cli.core import telemetry
from azure.cli.core.azclierror import ManualInterrupt, InvalidArgumentValueError, UnclassifiedUserFault, CLIInternalError, FileOperationError, ClientRequestError, DeploymentError, ValidationError, ArgumentUsageError, MutuallyExclusiveArgumentError, RequiredArgumentMissingError, ResourceNotFoundError
from azure.core.exceptions import HttpResponseError
from kubernetes import client as kube_client, config
from Crypto.IO import PEM
from Crypto.PublicKey import RSA
from Crypto.Util import asn1
from azext_connectedk8s._client_factory import _graph_client_factory
from azext_connectedk8s._client_factory import cf_resource_groups
from azext_connectedk8s._client_factory import resource_providers_client
from azext_connectedk8s._client_factory import get_graph_client_service_principals
from azext_connectedk8s._client_factory import cf_connected_cluster_prev_2022_10_01
from azext_connectedk8s._client_factory import cf_connectedmachine
import azext_connectedk8s._constants as consts
import azext_connectedk8s._utils as utils
import azext_connectedk8s._clientproxyutils as clientproxyutils
import azext_connectedk8s._troubleshootutils as troubleshootutils
import azext_connectedk8s._precheckutils as precheckutils
from glob import glob
from .vendored_sdks.models import ConnectedCluster, ConnectedClusterIdentity, ConnectedClusterPatch, ListClusterUserCredentialProperties
from .vendored_sdks.preview_2022_10_01.models import ConnectedCluster as ConnectedClusterPreview
from .vendored_sdks.preview_2022_10_01.models import ConnectedClusterPatch as ConnectedClusterPatchPreview
from threading import Timer, Thread
import sys
import hashlib
import re
logger = get_logger(__name__)
# pylint:disable=unused-argument
# pylint: disable=too-many-locals
# pylint: disable=too-many-branches
# pylint: disable=too-many-statements
# pylint: disable=line-too-long
def create_connectedk8s(cmd, client, resource_group_name, cluster_name, correlation_id=None, https_proxy="", http_proxy="", no_proxy="", proxy_cert="", location=None,
kube_config=None, kube_context=None, no_wait=False, tags=None, distribution='generic', infrastructure='generic',
disable_auto_upgrade=False, cl_oid=None, onboarding_timeout="600", enable_private_link=None, private_link_scope_resource_id=None,
distribution_version=None, azure_hybrid_benefit=None, yes=False, container_log_path=None):
logger.warning("This operation might take a while...\n")
# changing cli config to push telemetry in 1 hr interval
try:
if cmd.cli_ctx and hasattr(cmd.cli_ctx, 'config'):
cmd.cli_ctx.config.set_value('telemetry', 'push_interval_in_hours', '1')
except exception as e:
telemetry.set_exception(exception=e, fault_type=consts.Failed_To_Change_Telemetry_Push_Interval, summary="Failed to change the telemetry push interval to 1 hr")
# Validate custom token operation
custom_token_passed, location = utils.validate_custom_token(cmd, resource_group_name, location)
# Prompt for confirmation for few parameters
if enable_private_link is True:
confirmation_message = "The Cluster Connect and Custom Location features are not supported by Private Link at this time. Enabling Private Link will disable these features. Are you sure you want to continue?"
utils.user_confirmation(confirmation_message, yes)
if cl_oid:
logger.warning("Private Link is being enabled, and Custom Location is not supported by Private Link at this time, so the '--custom-locations-oid' parameter will be ignored.")
if azure_hybrid_benefit == "True":
confirmation_message = "I confirm I have an eligible Windows Server license with Azure Hybrid Benefit to apply this benefit to AKS on HCI or Windows Server. Visit https://aka.ms/ahb-aks for details"
utils.user_confirmation(confirmation_message, yes)
# Setting subscription id and tenant Id
subscription_id = os.getenv('AZURE_SUBSCRIPTION_ID') if custom_token_passed is True else get_subscription_id(cmd.cli_ctx)
if custom_token_passed is True:
onboarding_tenant_id = os.getenv('AZURE_TENANT_ID')
else:
account = Profile().get_subscription(subscription_id)
onboarding_tenant_id = account['homeTenantId']
resource_id = f'/subscriptions/{subscription_id}/resourcegroups/{resource_group_name}/providers/Microsoft.Kubernetes/connectedClusters/{cluster_name}/location/{location}'
telemetry.add_extension_event('connectedk8s', {'Context.Default.AzureCLI.resourceid': resource_id})
# Send cloud information to telemetry
azure_cloud = send_cloud_telemetry(cmd)
# Checking provider registration status
utils.check_provider_registrations(cmd.cli_ctx, subscription_id)
# Setting kubeconfig
kube_config = set_kube_config(kube_config)
# Escaping comma, forward slash present in https proxy urls, needed for helm params.
https_proxy = escape_proxy_settings(https_proxy)
# Escaping comma, forward slash present in http proxy urls, needed for helm params.
http_proxy = escape_proxy_settings(http_proxy)
# Escaping comma, forward slash present in no proxy urls, needed for helm params.
no_proxy = escape_proxy_settings(no_proxy)
# check whether proxy cert path exists
if proxy_cert != "" and (not os.path.exists(proxy_cert)):
telemetry.set_exception(exception='Proxy cert path does not exist', fault_type=consts.Proxy_Cert_Path_Does_Not_Exist_Fault_Type,
summary='Proxy cert path does not exist')
raise InvalidArgumentValueError(str.format(consts.Proxy_Cert_Path_Does_Not_Exist_Error, proxy_cert))
proxy_cert = proxy_cert.replace('\\', r'\\\\')
# Set preview client if latest preview properties are provided.
if enable_private_link is not None or distribution_version is not None or azure_hybrid_benefit is not None:
client = cf_connected_cluster_prev_2022_10_01(cmd.cli_ctx, None)
# Checking whether optional extra values file has been provided.
values_file_provided, values_file = utils.get_values_file()
# Validate the helm environment file for Dogfood.
dp_endpoint_dogfood = None
release_train_dogfood = None
if cmd.cli_ctx.cloud.endpoints.resource_manager == consts.Dogfood_RMEndpoint:
azure_cloud = consts.Azure_DogfoodCloudName
dp_endpoint_dogfood, release_train_dogfood = validate_env_file_dogfood(values_file, values_file_provided)
# Loading the kubeconfig file in kubernetes client configuration
load_kube_config(kube_config, kube_context)
# Checking the connection to kubernetes cluster.
# This check was added to avoid large timeouts when connecting to AAD Enabled AKS clusters
# if the user had not logged in.
kubernetes_version = check_kube_connection()
utils.try_list_node_fix()
api_instance = kube_client.CoreV1Api()
node_api_response = utils.validate_node_api_response(api_instance, None)
is_arm64_cluster = check_arm64_node(node_api_response)
required_node_exists = check_linux_node(node_api_response)
# Pre onboarding checks
try:
kubectl_client_location = install_kubectl_client()
helm_client_location = install_helm_client()
diagnostic_checks = "Failed"
batchv1_api_instance = kube_client.BatchV1Api()
storage_space_available = True
current_time = time.ctime(time.time())
time_stamp = ""
for elements in current_time:
if(elements == ' '):
time_stamp += '-'
continue
elif(elements == ':'):
time_stamp += '.'
continue
time_stamp += elements
time_stamp = cluster_name + '-' + time_stamp
# Generate the diagnostic folder in a given location
filepath_with_timestamp, diagnostic_folder_status = utils.create_folder_diagnosticlogs(time_stamp, consts.Pre_Onboarding_Check_Logs)
if(diagnostic_folder_status is not True):
storage_space_available = False
# Performing cluster-diagnostic-checks
diagnostic_checks, storage_space_available = precheckutils.fetch_diagnostic_checks_results(api_instance, batchv1_api_instance, helm_client_location, kubectl_client_location, kube_config, kube_context, location, http_proxy, https_proxy, no_proxy, proxy_cert, azure_cloud, filepath_with_timestamp, storage_space_available)
precheckutils.fetching_cli_output_logs(filepath_with_timestamp, storage_space_available, 1)
if storage_space_available is False:
logger.warning("There is no storage space available on your device and hence not saving cluster diagnostic check logs on your device")
except Exception as e:
telemetry.set_exception(exception="An exception has occured while trying to execute pre-onboarding diagnostic checks : {}".format(str(e)),
fault_type=consts.Pre_Onboarding_Diagnostic_Checks_Execution_Failed, summary="An exception has occured while trying to execute pre-onboarding diagnostic checks : {}".format(str(e)))
raise CLIInternalError("An exception has occured while trying to execute pre-onboarding diagnostic checks : {}".format(str(e)))
# Handling the user manual interrupt
except KeyboardInterrupt:
try:
troubleshootutils.fetching_cli_output_logs(filepath_with_timestamp, storage_space_available, 0)
except Exception as e:
pass
raise ManualInterrupt('Process terminated externally.')
# If the checks didnt pass then stop the onboarding
if diagnostic_checks != consts.Diagnostic_Check_Passed:
if storage_space_available:
logger.warning("The pre-check result logs logs have been saved at this path:" + filepath_with_timestamp + " .\nThese logs can be attached while filing a support ticket for further assistance.\n")
if(diagnostic_checks == consts.Diagnostic_Check_Incomplete):
telemetry.set_exception(exception='Cluster Diagnostic Prechecks Incomplete', fault_type=consts.Cluster_Diagnostic_Prechecks_Incomplete, summary="Cluster Diagnostic Prechecks didnt complete in the cluster")
raise ValidationError("Execution of pre-onboarding checks failed and hence not proceeding with cluster onboarding. Please meet the prerequisites - 'https://learn.microsoft.com/en-us/azure/azure-arc/kubernetes/quickstart-connect-cluster?tabs=azure-cli%2Cazure-cloud#prerequisites' and try onboarding again.")
else:
telemetry.set_exception(exception='Cluster Diagnostic Prechecks Failed', fault_type=consts.Cluster_Diagnostic_Prechecks_Failed, summary="Cluster Diagnostic Prechecks Failed in the cluster")
raise ValidationError("One or more pre-onboarding diagnostic checks failed and hence not proceeding with cluster onboarding. Please resolve them and try onboarding again.")
print("The required pre-checks for onboarding have succeeded.")
if not required_node_exists:
telemetry.set_user_fault()
telemetry.set_exception(exception="Couldn't find any node on the kubernetes cluster with the OS 'linux'", fault_type=consts.Linux_Node_Not_Exists,
summary="Couldn't find any node on the kubernetes cluster with the OS 'linux'")
logger.warning("Please ensure that this Kubernetes cluster have any nodes with OS 'linux', for scheduling the Arc-Agents onto and connecting to Azure. Learn more at {}".format("https://aka.ms/ArcK8sSupportedOSArchitecture"))
crb_permission = utils.can_create_clusterrolebindings()
if not crb_permission:
telemetry.set_exception(exception="Your credentials doesn't have permission to create clusterrolebindings on this kubernetes cluster.", fault_type=consts.Cannot_Create_ClusterRoleBindings_Fault_Type,
summary="Your credentials doesn't have permission to create clusterrolebindings on this kubernetes cluster.")
raise ValidationError("Your credentials doesn't have permission to create clusterrolebindings on this kubernetes cluster. Please check your permissions.")
# Get kubernetes cluster info
if distribution == 'generic':
kubernetes_distro = get_kubernetes_distro(node_api_response) # (cluster heuristics)
else:
kubernetes_distro = distribution
if infrastructure == 'generic':
kubernetes_infra = get_kubernetes_infra(node_api_response) # (cluster heuristics)
else:
kubernetes_infra = infrastructure
kubernetes_properties = {
'Context.Default.AzureCLI.KubernetesVersion': kubernetes_version,
'Context.Default.AzureCLI.KubernetesDistro': kubernetes_distro,
'Context.Default.AzureCLI.KubernetesInfra': kubernetes_infra
}
telemetry.add_extension_event('connectedk8s', kubernetes_properties)
# Checking if it is an AKS cluster
is_aks_cluster = check_aks_cluster(kube_config, kube_context)
if is_aks_cluster:
logger.warning("Connecting an Azure Kubernetes Service (AKS) cluster to Azure Arc is only required for running Arc enabled services like App Services and Data Services on the cluster. Other features like Azure Monitor and Azure Defender are natively available on AKS. Learn more at {}.".format(" https://go.microsoft.com/fwlink/?linkid=2144200"))
# Install helm client
helm_client_location = install_helm_client()
# Validate location
utils.validate_location(cmd, location)
resourceClient = cf_resource_groups(cmd.cli_ctx, subscription_id=subscription_id)
# Validate location of private link scope resource. Throws error only if there is a location mismatch
if enable_private_link is True:
try:
pls_arm_id_arr = private_link_scope_resource_id.split('/')
hc_client = cf_connectedmachine(cmd.cli_ctx, pls_arm_id_arr[2])
pls_get_result = hc_client.get(pls_arm_id_arr[4], pls_arm_id_arr[8])
pls_location = pls_get_result.location.lower()
if pls_location != location.lower():
telemetry.set_exception(exception='Connected cluster resource and Private link scope resource are present in different locations',
fault_type=consts.Pls_Location_Mismatch_Fault_Type, summary='Pls resource location mismatch')
raise ArgumentUsageError("The location of the private link scope resource does not match the location of connected cluster resource. Please ensure that both the resources are in the same azure location.")
except ArgumentUsageError as argex:
raise(argex)
except Exception as ex:
if isinstance(ex, HttpResponseError):
status_code = ex.response.status_code
if status_code == 404:
telemetry.set_exception(exception='Private link scope resource does not exist',
fault_type=consts.Pls_Resource_Not_Found, summary='Pls resource does not exist')
raise ArgumentUsageError("The private link scope resource '{}' does not exist. Please ensure that you pass a valid ARM Resource Id.".format(private_link_scope_resource_id))
logger.warning("Error occured while checking the private link scope resource location: %s\n", ex)
# Check Release Existance
release_namespace = utils.get_release_namespace(kube_config, kube_context, helm_client_location)
if release_namespace:
# Loading config map
api_instance = kube_client.CoreV1Api()
try:
configmap = api_instance.read_namespaced_config_map('azure-clusterconfig', 'azure-arc')
except Exception as e: # pylint: disable=broad-except
utils.kubernetes_exception_handler(e, consts.Read_ConfigMap_Fault_Type, 'Unable to read ConfigMap',
error_message="Unable to read ConfigMap 'azure-clusterconfig' in 'azure-arc' namespace: ",
message_for_not_found="The helm release 'azure-arc' is present but the azure-arc namespace/configmap is missing. Please run 'helm delete azure-arc --namespace {} --no-hooks' to cleanup the release before onboarding the cluster again.".format(release_namespace))
configmap_rg_name = configmap.data["AZURE_RESOURCE_GROUP"]
configmap_cluster_name = configmap.data["AZURE_RESOURCE_NAME"]
if connected_cluster_exists(client, configmap_rg_name, configmap_cluster_name):
if (configmap_rg_name.lower() == resource_group_name.lower() and
configmap_cluster_name.lower() == cluster_name.lower()):
# Re-put connected cluster
try:
public_key = client.get(configmap_rg_name,
configmap_cluster_name).agent_public_key_certificate
except Exception as e: # pylint: disable=broad-except
utils.arm_exception_handler(e, consts.Get_ConnectedCluster_Fault_Type, 'Failed to check if connected cluster resource already exists.')
cc = generate_request_payload(location, public_key, tags, kubernetes_distro, kubernetes_infra, enable_private_link, private_link_scope_resource_id, distribution_version, azure_hybrid_benefit)
cc_response = create_cc_resource(client, resource_group_name, cluster_name, cc, no_wait)
cc_response = LongRunningOperation(cmd.cli_ctx)(cc_response)
# Disabling cluster-connect if private link is getting enabled
if enable_private_link is True:
disable_cluster_connect(cmd, client, resource_group_name, cluster_name, kube_config, kube_context, values_file, values_file_provided, dp_endpoint_dogfood, release_train_dogfood, release_namespace, helm_client_location)
return cc_response
else:
telemetry.set_exception(exception='The kubernetes cluster is already onboarded', fault_type=consts.Cluster_Already_Onboarded_Fault_Type,
summary='Kubernetes cluster already onboarded')
raise ArgumentUsageError("The kubernetes cluster you are trying to onboard " +
"is already onboarded to the resource group" +
" '{}' with resource name '{}'.".format(configmap_rg_name, configmap_cluster_name))
else:
logger.warning("Cleaning up the stale arc agents present on the cluster before starting new onboarding.")
# Explicit CRD Deletion
crd_cleanup_force_delete(kubectl_client_location, kube_config, kube_context)
# Cleaning up the cluster
utils.delete_arc_agents(release_namespace, kube_config, kube_context, helm_client_location, is_arm64_cluster, True)
else:
if connected_cluster_exists(client, resource_group_name, cluster_name):
telemetry.set_exception(exception='The connected cluster resource already exists', fault_type=consts.Resource_Already_Exists_Fault_Type,
summary='Connected cluster resource already exists')
raise ArgumentUsageError("The connected cluster resource {} already exists ".format(cluster_name) +
"in the resource group {} ".format(resource_group_name) +
"and corresponds to a different Kubernetes cluster.", recommendation="To onboard this Kubernetes cluster " +
"to Azure, specify different resource name or resource group name.")
else:
# cleanup of stuck CRD if release namespace is not present/deleted
crd_cleanup_force_delete(kubectl_client_location, kube_config, kube_context)
# Resource group Creation
if resource_group_exists(cmd.cli_ctx, resource_group_name, subscription_id) is False:
from azure.cli.core.profiles import ResourceType
ResourceGroup = cmd.get_models('ResourceGroup', resource_type=ResourceType.MGMT_RESOURCE_RESOURCES)
parameters = ResourceGroup(location=location)
try:
resourceClient.create_or_update(resource_group_name, parameters)
except Exception as e: # pylint: disable=broad-except
utils.arm_exception_handler(e, consts.Create_ResourceGroup_Fault_Type, 'Failed to create the resource group')
# Adding helm repo
if os.getenv('HELMREPONAME') and os.getenv('HELMREPOURL'):
utils.add_helm_repo(kube_config, kube_context, helm_client_location)
# Setting the config dataplane endpoint
config_dp_endpoint = get_config_dp_endpoint(cmd, location)
# Retrieving Helm chart OCI Artifact location
registry_path = os.getenv('HELMREGISTRY') if os.getenv('HELMREGISTRY') else utils.get_helm_registry(cmd, config_dp_endpoint, dp_endpoint_dogfood, release_train_dogfood)
# Get azure-arc agent version for telemetry
azure_arc_agent_version = registry_path.split(':')[1]
telemetry.add_extension_event('connectedk8s', {'Context.Default.AzureCLI.AgentVersion': azure_arc_agent_version})
# Get helm chart path
chart_path = utils.get_chart_path(registry_path, kube_config, kube_context, helm_client_location)
# Generate public-private key pair
try:
key_pair = RSA.generate(4096)
except Exception as e:
telemetry.set_exception(exception=e, fault_type=consts.KeyPair_Generate_Fault_Type,
summary='Failed to generate public-private key pair')
raise CLIInternalError("Failed to generate public-private key pair. " + str(e))
try:
public_key = get_public_key(key_pair)
except Exception as e:
telemetry.set_exception(exception=e, fault_type=consts.PublicKey_Export_Fault_Type,
summary='Failed to export public key')
raise CLIInternalError("Failed to export public key." + str(e))
try:
private_key_pem = get_private_key(key_pair)
except Exception as e:
telemetry.set_exception(exception=e, fault_type=consts.PrivateKey_Export_Fault_Type,
summary='Failed to export private key')
raise CLIInternalError("Failed to export private key." + str(e))
# Generate request payload
cc = generate_request_payload(location, public_key, tags, kubernetes_distro, kubernetes_infra, enable_private_link, private_link_scope_resource_id, distribution_version, azure_hybrid_benefit)
print("Azure resource provisioning has begun.")
# Create connected cluster resource
put_cc_response = create_cc_resource(client, resource_group_name, cluster_name, cc, no_wait)
put_cc_response = LongRunningOperation(cmd.cli_ctx)(put_cc_response)
print("Azure resource provisioning has finished.")
# Checking if custom locations rp is registered and fetching oid if it is registered
enable_custom_locations, custom_locations_oid = check_cl_registration_and_get_oid(cmd, cl_oid, subscription_id)
print("Starting to install Azure arc agents on the Kubernetes cluster.")
# Install azure-arc agents
utils.helm_install_release(chart_path, subscription_id, kubernetes_distro, kubernetes_infra, resource_group_name, cluster_name,
location, onboarding_tenant_id, http_proxy, https_proxy, no_proxy, proxy_cert, private_key_pem, kube_config,
kube_context, no_wait, values_file_provided, values_file, azure_cloud, disable_auto_upgrade, enable_custom_locations,
custom_locations_oid, helm_client_location, enable_private_link, onboarding_timeout, container_log_path)
return put_cc_response
def send_cloud_telemetry(cmd):
telemetry.add_extension_event('connectedk8s', {'Context.Default.AzureCLI.AzureCloud': cmd.cli_ctx.cloud.name})
cloud_name = cmd.cli_ctx.cloud.name.upper()
# Setting cloud name to format that is understood by golang SDK.
if cloud_name == consts.PublicCloud_OriginalName:
cloud_name = consts.Azure_PublicCloudName
elif cloud_name == consts.USGovCloud_OriginalName:
cloud_name = consts.Azure_USGovCloudName
return cloud_name
def validate_env_file_dogfood(values_file, values_file_provided):
if not values_file_provided:
telemetry.set_exception(exception='Helm environment file not provided', fault_type=consts.Helm_Environment_File_Fault_Type,
summary='Helm environment file missing')
raise ValidationError("Helm environment file is required when using Dogfood environment for onboarding the cluster.", recommendation="Please set the environment variable 'HELMVALUESPATH' to point to the file.")
with open(values_file, 'r') as f:
try:
env_dict = yaml.safe_load(f)
except Exception as e:
telemetry.set_exception(exception=e, fault_type=consts.Helm_Environment_File_Fault_Type,
summary='Problem loading the helm environment file')
raise FileOperationError("Problem loading the helm environment file: " + str(e))
try:
assert env_dict.get('global').get('azureEnvironment') == 'AZUREDOGFOOD'
assert env_dict.get('systemDefaultValues').get('azureArcAgents').get('config_dp_endpoint_override')
except Exception as e:
telemetry.set_exception(exception=e, fault_type=consts.Helm_Environment_File_Fault_Type,
summary='Problem loading the helm environment variables')
raise FileOperationError("The required helm environment variables for dogfood onboarding are either not present in the file or incorrectly set.", recommendation="Please check the values 'global.azureEnvironment' and 'systemDefaultValues.azureArcAgents.config_dp_endpoint_override' in the file.")
# Return the dp endpoint and release train
dp_endpoint = env_dict.get('systemDefaultValues').get('azureArcAgents').get('config_dp_endpoint_override')
release_train = env_dict.get('systemDefaultValues').get('azureArcAgents').get('releaseTrain')
return dp_endpoint, release_train
def set_kube_config(kube_config):
if kube_config:
# Trim kubeconfig. This is required for windows os.
if (kube_config.startswith("'") or kube_config.startswith('"')):
kube_config = kube_config[1:]
if (kube_config.endswith("'") or kube_config.endswith('"')):
kube_config = kube_config[:-1]
return kube_config
return None
def escape_proxy_settings(proxy_setting):
if proxy_setting is None:
return ""
proxy_setting = proxy_setting.replace(',', r'\,')
proxy_setting = proxy_setting.replace('/', r'\/')
return proxy_setting
def check_kube_connection():
api_instance = kube_client.VersionApi()
try:
api_response = api_instance.get_code()
return api_response.git_version
except Exception as e: # pylint: disable=broad-except
logger.warning("Unable to verify connectivity to the Kubernetes cluster.")
utils.kubernetes_exception_handler(e, consts.Kubernetes_Connectivity_FaultType, 'Unable to verify connectivity to the Kubernetes cluster')
def install_helm_client():
# Return helm client path set by user
if os.getenv('HELM_CLIENT_PATH'):
return os.getenv('HELM_CLIENT_PATH')
# Fetch system related info
operating_system = platform.system().lower()
machine_type = platform.machine()
# Send machine telemetry
telemetry.add_extension_event('connectedk8s', {'Context.Default.AzureCLI.MachineType': machine_type})
# Set helm binary download & install locations
if(operating_system == 'windows'):
download_location_string = f'.azure\\helm\\{consts.HELM_VERSION}\\helm-{consts.HELM_VERSION}-{operating_system}-amd64.zip'
install_location_string = f'.azure\\helm\\{consts.HELM_VERSION}\\{operating_system}-amd64\\helm.exe'
requestUri = f'{consts.HELM_STORAGE_URL}/helm/helm-{consts.HELM_VERSION}-{operating_system}-amd64.zip'
elif(operating_system == 'linux' or operating_system == 'darwin'):
download_location_string = f'.azure/helm/{consts.HELM_VERSION}/helm-{consts.HELM_VERSION}-{operating_system}-amd64.tar.gz'
install_location_string = f'.azure/helm/{consts.HELM_VERSION}/{operating_system}-amd64/helm'
requestUri = f'{consts.HELM_STORAGE_URL}/helm/helm-{consts.HELM_VERSION}-{operating_system}-amd64.tar.gz'
else:
telemetry.set_exception(exception='Unsupported OS for installing helm client', fault_type=consts.Helm_Unsupported_OS_Fault_Type,
summary=f'{operating_system} is not supported for installing helm client')
raise ClientRequestError(f'The {operating_system} platform is not currently supported for installing helm client.')
download_location = os.path.expanduser(os.path.join('~', download_location_string))
download_dir = os.path.dirname(download_location)
install_location = os.path.expanduser(os.path.join('~', install_location_string))
# Download compressed halm binary if not already present
if not os.path.isfile(download_location):
# Creating the helm folder if it doesnt exist
if not os.path.exists(download_dir):
try:
os.makedirs(download_dir)
except Exception as e:
telemetry.set_exception(exception=e, fault_type=consts.Create_Directory_Fault_Type,
summary='Unable to create helm directory')
raise ClientRequestError("Failed to create helm directory." + str(e))
# Downloading compressed helm client executable
logger.warning("Downloading helm client for first time. This can take few minutes...")
retry_count = 3
retry_delay = 5
for i in range(retry_count):
try:
response = urllib.request.urlopen(requestUri)
break
except Exception as e:
if i == retry_count - 1:
if "Connection reset by peer" in str(e):
telemetry.set_user_fault()
telemetry.set_exception(exception=e, fault_type=consts.Download_Helm_Fault_Type,
summary='Unable to download helm client.')
raise CLIInternalError("Failed to download helm client.", recommendation="Please check your internet connection." + str(e))
time.sleep(retry_delay)
responseContent = response.read()
response.close()
# Creating the compressed helm binaries
try:
with open(download_location, 'wb') as f:
f.write(responseContent)
except Exception as e:
telemetry.set_exception(exception=e, fault_type=consts.Create_HelmExe_Fault_Type,
summary='Unable to create helm executable')
raise ClientRequestError("Failed to create helm executable." + str(e), recommendation="Please ensure that you delete the directory '{}' before trying again.".format(download_dir))
# Extract compressed helm binary
if not os.path.isfile(install_location):
try:
shutil.unpack_archive(download_location, download_dir)
os.chmod(install_location, os.stat(install_location).st_mode | stat.S_IXUSR)
except Exception as e:
telemetry.set_exception(exception=e, fault_type=consts.Extract_HelmExe_Fault_Type,
summary='Unable to extract helm executable')
raise ClientRequestError("Failed to extract helm executable." + str(e), recommendation="Please ensure that you delete the directory '{}' before trying again.".format(download_dir))
return install_location
def resource_group_exists(ctx, resource_group_name, subscription_id=None):
groups = cf_resource_groups(ctx, subscription_id=subscription_id)
try:
groups.get(resource_group_name)
return True
except: # pylint: disable=bare-except
return False
def connected_cluster_exists(client, resource_group_name, cluster_name):
try:
client.get(resource_group_name, cluster_name)
except Exception as e: # pylint: disable=broad-except
utils.arm_exception_handler(e, consts.Get_ConnectedCluster_Fault_Type, 'Failed to check if connected cluster resource already exists.', return_if_not_found=True)
return False
return True
def get_config_dp_endpoint(cmd, location):
cloud_based_domain = cmd.cli_ctx.cloud.endpoints.active_directory.split('.')[2]
config_dp_endpoint = "https://{}.dp.kubernetesconfiguration.azure.{}".format(location, cloud_based_domain)
return config_dp_endpoint
def get_public_key(key_pair):
pubKey = key_pair.publickey()
seq = asn1.DerSequence([pubKey.n, pubKey.e])
enc = seq.encode()
return b64encode(enc).decode('utf-8')
def load_kube_config(kube_config, kube_context):
try:
config.load_kube_config(config_file=kube_config, context=kube_context)
except Exception as e:
telemetry.set_exception(exception=e, fault_type=consts.Load_Kubeconfig_Fault_Type,
summary='Problem loading the kubeconfig file')
raise FileOperationError("Problem loading the kubeconfig file." + str(e))
def get_private_key(key_pair):
privKey_DER = key_pair.exportKey(format='DER')
return PEM.encode(privKey_DER, "RSA PRIVATE KEY")
def get_kubernetes_distro(api_response): # Heuristic
if api_response is None:
return "generic"
try:
for node in api_response.items:
labels = node.metadata.labels
provider_id = str(node.spec.provider_id)
annotations = node.metadata.annotations
if labels.get("node.openshift.io/os_id"):
return "openshift"
if labels.get("kubernetes.azure.com/node-image-version"):
return "aks"
if labels.get("cloud.google.com/gke-nodepool") or labels.get("cloud.google.com/gke-os-distribution"):
return "gke"
if labels.get("eks.amazonaws.com/nodegroup"):
return "eks"
if labels.get("minikube.k8s.io/version"):
return "minikube"
if provider_id.startswith("kind://"):
return "kind"
if provider_id.startswith("k3s://"):
return "k3s"
if annotations.get("rke.cattle.io/external-ip") or annotations.get("rke.cattle.io/internal-ip"):
return "rancher_rke"
return "generic"
except Exception as e: # pylint: disable=broad-except
logger.debug("Error occured while trying to fetch kubernetes distribution: " + str(e))
utils.kubernetes_exception_handler(e, consts.Get_Kubernetes_Distro_Fault_Type, 'Unable to fetch kubernetes distribution',
raise_error=False)
return "generic"
def get_kubernetes_infra(api_response): # Heuristic
if api_response is None:
return "generic"
try:
for node in api_response.items:
provider_id = str(node.spec.provider_id)
infra = provider_id.split(':')[0]
if infra == "k3s" or infra == "kind":
return "generic"
if infra == "azure":
return "azure"
if infra == "gce":
return "gcp"
if infra == "aws":
return "aws"
k8s_infra = utils.validate_infrastructure_type(infra)
if k8s_infra is not None:
return k8s_infra
return "generic"
except Exception as e: # pylint: disable=broad-except
logger.debug("Error occured while trying to fetch kubernetes infrastructure: " + str(e))
utils.kubernetes_exception_handler(e, consts.Get_Kubernetes_Infra_Fault_Type, 'Unable to fetch kubernetes infrastructure',
raise_error=False)
return "generic"
def check_linux_node(api_response):
try:
for item in api_response.items:
node_os = item.metadata.labels.get("kubernetes.io/os")
if node_os == "linux":
return True
except Exception as e: # pylint: disable=broad-except
logger.debug("Error occured while trying to find a linux node: " + str(e))
utils.kubernetes_exception_handler(e, consts.Kubernetes_Node_Type_Fetch_Fault_OS, 'Unable to find a linux node',
raise_error=False)
return False
def check_arm64_node(api_response):
try:
for item in api_response.items:
node_arch = item.metadata.labels.get("kubernetes.io/arch")
if node_arch == "arm64":
return True
except Exception as e: # pylint: disable=broad-except
logger.debug("Error occured while trying to find an arm64 node: " + str(e))
utils.kubernetes_exception_handler(e, consts.Kubernetes_Node_Type_Fetch_Fault_Arch, 'Unable to find an arm64 node',
raise_error=False)
return False
def generate_request_payload(location, public_key, tags, kubernetes_distro, kubernetes_infra, enable_private_link, private_link_scope_resource_id, distribution_version, azure_hybrid_benefit):
# Create connected cluster resource object
identity = ConnectedClusterIdentity(
type="SystemAssigned"
)
if tags is None:
tags = {}
cc = ConnectedCluster(
location=location,
identity=identity,
agent_public_key_certificate=public_key,
tags=tags,
distribution=kubernetes_distro,
infrastructure=kubernetes_infra
)
if enable_private_link is not None or distribution_version is not None or azure_hybrid_benefit is not None:
private_link_state = None
if enable_private_link is not None:
private_link_state = "Enabled" if enable_private_link is True else "Disabled"
cc = ConnectedClusterPreview(
location=location,
identity=identity,
agent_public_key_certificate=public_key,
tags=tags,
distribution=kubernetes_distro,
infrastructure=kubernetes_infra,
private_link_scope_resource_id=private_link_scope_resource_id,
private_link_state=private_link_state,
azure_hybrid_benefit=azure_hybrid_benefit,
distribution_version=distribution_version
)
return cc
def generate_patch_payload(tags, distribution, distribution_version, azure_hybrid_benefit):
cc = ConnectedClusterPatchPreview(
tags=tags,
distribution=distribution,
distribution_version=distribution_version,
azure_hybrid_benefit=azure_hybrid_benefit
)
return cc
def get_kubeconfig_node_dict(kube_config=None):
if kube_config is None:
kube_config = os.getenv('KUBECONFIG') if os.getenv('KUBECONFIG') else os.path.join(os.path.expanduser('~'), '.kube', 'config')
try:
kubeconfig_data = config.kube_config._get_kube_config_loader_for_yaml_file(kube_config)._config
except Exception as ex:
telemetry.set_exception(exception=ex, fault_type=consts.Load_Kubeconfig_Fault_Type,
summary='Error while fetching details from kubeconfig')
raise FileOperationError("Error while fetching details from kubeconfig." + str(ex))
return kubeconfig_data
def check_proxy_kubeconfig(kube_config, kube_context, arm_hash):
server_address = get_server_address(kube_config, kube_context)
regex_string = r'https://127.0.0.1:[0-9]{1,5}/' + arm_hash
p = re.compile(regex_string)
if p.fullmatch(server_address) is not None:
return True
else:
return False
def check_aks_cluster(kube_config, kube_context):
server_address = get_server_address(kube_config, kube_context)
if server_address.find(".azmk8s.io:") == -1:
return False
else:
return True
def get_server_address(kube_config, kube_context):
config_data = get_kubeconfig_node_dict(kube_config=kube_config)
try:
all_contexts, current_context = config.list_kube_config_contexts(config_file=kube_config)
except Exception as e: # pylint: disable=broad-except
logger.warning("Exception while trying to list kube contexts: %s\n", e)
if kube_context is None:
# Get name of the cluster from current context as kube_context is none.
cluster_name = current_context.get('context').get('cluster')
if cluster_name is None:
logger.warning("Cluster not found in currentcontext: " + str(current_context))
else:
cluster_found = False
for context in all_contexts:
if context.get('name') == kube_context:
cluster_found = True
cluster_name = context.get('context').get('cluster')
break
if not cluster_found or cluster_name is None:
logger.warning("Cluster not found in kubecontext: " + str(kube_context))
clusters = config_data.safe_get('clusters')
server_address = ""
for cluster in clusters:
if cluster.safe_get('name') == cluster_name:
server_address = cluster.safe_get('cluster').get('server')
break
return server_address
def get_connectedk8s(cmd, client, resource_group_name, cluster_name):
# Override preview client to show private link properties to customers
client = cf_connected_cluster_prev_2022_10_01(cmd.cli_ctx, None)
return client.get(resource_group_name, cluster_name)
def list_connectedk8s(cmd, client, resource_group_name=None):
# Override preview client to show private link properties to customers
client = cf_connected_cluster_prev_2022_10_01(cmd.cli_ctx, None)
if not resource_group_name:
return client.list_by_subscription()
return client.list_by_resource_group(resource_group_name)
def delete_connectedk8s(cmd, client, resource_group_name, cluster_name,
kube_config=None, kube_context=None, no_wait=False, force_delete=False, yes=False):
# The force delete prompt is added because it can be used in the case where the config map is missing
# so we cannot check if the user context is pointing to the cluster that he intends to delete
if not force_delete:
confirmation_message = "Are you sure you want to perform delete operation?"
utils.user_confirmation(confirmation_message, yes)
elif force_delete:
confirmation_message = "Force delete will clean up all the azure-arc resources, including extensions. Please make sure your current kubeconfig is pointing to the right cluster.\n" + "Are you sure you want to perform force delete:"
utils.user_confirmation(confirmation_message, yes)
logger.warning("This operation might take a while ...\n")
# Send cloud information to telemetry
send_cloud_telemetry(cmd)
# Setting kubeconfig
kube_config = set_kube_config(kube_config)
# Loading the kubeconfig file in kubernetes client configuration
load_kube_config(kube_config, kube_context)
# Checking the connection to kubernetes cluster.
# This check was added to avoid large timeouts when connecting to AAD Enabled
# AKS clusters if the user had not logged in.
check_kube_connection()
# Install helm client
helm_client_location = install_helm_client()
# Check Release Existance
release_namespace = utils.get_release_namespace(kube_config, kube_context, helm_client_location)
utils.try_list_node_fix()
api_instance = kube_client.CoreV1Api()
node_api_response = utils.validate_node_api_response(api_instance, None)
is_arm64_cluster = check_arm64_node(node_api_response)
# Check forced delete flag
if(force_delete):
kubectl_client_location = install_kubectl_client()
delete_cc_resource(client, resource_group_name, cluster_name, no_wait).result()
# Explicit CRD Deletion
crd_cleanup_force_delete(kubectl_client_location, kube_config, kube_context)
if(release_namespace):
utils.delete_arc_agents(release_namespace, kube_config, kube_context, helm_client_location, is_arm64_cluster, True)
return
if not release_namespace:
delete_cc_resource(client, resource_group_name, cluster_name, no_wait).result()
return
# Loading config map
try:
configmap = api_instance.read_namespaced_config_map('azure-clusterconfig', 'azure-arc')
except Exception as e: # pylint: disable=broad-except
utils.kubernetes_exception_handler(e, consts.Read_ConfigMap_Fault_Type, 'Unable to read ConfigMap',
error_message="Unable to read ConfigMap 'azure-clusterconfig' in 'azure-arc' namespace: ",
message_for_not_found="The helm release 'azure-arc' is present but the azure-arc namespace/configmap is missing. Please run 'helm delete azure-arc --namepace {} --no-hooks' to cleanup the release before onboarding the cluster again.".format(release_namespace))
subscription_id = os.getenv('AZURE_SUBSCRIPTION_ID') if os.getenv('AZURE_ACCESS_TOKEN') else get_subscription_id(cmd.cli_ctx)
if (configmap.data["AZURE_RESOURCE_GROUP"].lower() == resource_group_name.lower() and
configmap.data["AZURE_RESOURCE_NAME"].lower() == cluster_name.lower() and configmap.data["AZURE_SUBSCRIPTION_ID"].lower() == subscription_id.lower()):
armid = "/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Kubernetes/connectedClusters/{}".format(subscription_id, resource_group_name, cluster_name)
arm_hash = hashlib.sha256(armid.lower().encode('utf-8')).hexdigest()
if check_proxy_kubeconfig(kube_config, kube_context, arm_hash):
telemetry.set_exception(exception='Encountered proxy kubeconfig during deletion.', fault_type=consts.Proxy_Kubeconfig_During_Deletion_Fault_Type,
summary='The resource cannot be deleted as user is using proxy kubeconfig.')
raise ClientRequestError("az connectedk8s delete is not supported when using the Cluster Connect kubeconfig.", recommendation="Run the az connectedk8s delete command with your kubeconfig file pointing to the actual Kubernetes cluster to ensure that the agents are cleaned up successfully as part of the delete command.")
delete_cc_resource(client, resource_group_name, cluster_name, no_wait).result()
else:
telemetry.set_exception(exception='Unable to delete connected cluster', fault_type=consts.Bad_DeleteRequest_Fault_Type,
summary='The resource cannot be deleted as kubernetes cluster is onboarded with some other resource id')
raise ArgumentUsageError("The current context in the kubeconfig file does not correspond " +
"to the connected cluster resource specified. Agents installed on this cluster correspond " +
"to the resource group name '{}' ".format(configmap.data["AZURE_RESOURCE_GROUP"]) +
"and resource name '{}'.".format(configmap.data["AZURE_RESOURCE_NAME"]))
# Deleting the azure-arc agents
utils.delete_arc_agents(release_namespace, kube_config, kube_context, helm_client_location, is_arm64_cluster)
def create_cc_resource(client, resource_group_name, cluster_name, cc, no_wait):
try:
return sdk_no_wait(no_wait, client.begin_create, resource_group_name=resource_group_name,
cluster_name=cluster_name, connected_cluster=cc)
except Exception as e:
utils.arm_exception_handler(e, consts.Create_ConnectedCluster_Fault_Type, 'Unable to create connected cluster resource')
def patch_cc_resource(client, resource_group_name, cluster_name, cc):
try:
return client.update(resource_group_name=resource_group_name,
cluster_name=cluster_name, connected_cluster_patch=cc)
except Exception as e:
utils.arm_exception_handler(e, consts.Update_ConnectedCluster_Fault_Type, 'Unable to update connected cluster resource')
def delete_cc_resource(client, resource_group_name, cluster_name, no_wait):
try:
return sdk_no_wait(no_wait, client.begin_delete,
resource_group_name=resource_group_name,
cluster_name=cluster_name)
except Exception as e:
utils.arm_exception_handler(e, consts.Delete_ConnectedCluster_Fault_Type, 'Unable to delete connected cluster resource')
def update_connected_cluster_internal(client, resource_group_name, cluster_name, tags=None, distribution=None, distribution_version=None, azure_hybrid_benefit=None):
cc = generate_patch_payload(tags, distribution, distribution_version, azure_hybrid_benefit)
return patch_cc_resource(client, resource_group_name, cluster_name, cc)
# pylint:disable=unused-argument
# pylint: disable=too-many-locals
# pylint: disable=too-many-branches
# pylint: disable=too-many-statements
# pylint: disable=line-too-long
def update_connected_cluster(cmd, client, resource_group_name, cluster_name, https_proxy="", http_proxy="", no_proxy="", proxy_cert="",
disable_proxy=False, kube_config=None, kube_context=None, auto_upgrade=None, tags=None,
distribution=None, distribution_version=None, azure_hybrid_benefit=None, yes=False, container_log_path=None):
# Prompt for confirmation for few parameters
if azure_hybrid_benefit == "True":
confirmation_message = "I confirm I have an eligible Windows Server license with Azure Hybrid Benefit to apply this benefit to AKS on HCI or Windows Server. Visit https://aka.ms/ahb-aks for details"
utils.user_confirmation(confirmation_message, yes)
# Send cloud information to telemetry
send_cloud_telemetry(cmd)
# Setting kubeconfig
kube_config = set_kube_config(kube_config)
# Escaping comma, forward slash present in https proxy urls, needed for helm params.
https_proxy = escape_proxy_settings(https_proxy)
# Escaping comma, forward slash present in http proxy urls, needed for helm params.
http_proxy = escape_proxy_settings(http_proxy)
# Escaping comma, forward slash present in no proxy urls, needed for helm params.
no_proxy = escape_proxy_settings(no_proxy)
# check whether proxy cert path exists
if proxy_cert != "" and (not os.path.exists(proxy_cert)):
telemetry.set_exception(exception='Proxy cert path does not exist', fault_type=consts.Proxy_Cert_Path_Does_Not_Exist_Fault_Type,
summary='Proxy cert path does not exist')
raise InvalidArgumentValueError(str.format(consts.Proxy_Cert_Path_Does_Not_Exist_Error, proxy_cert))
proxy_cert = proxy_cert.replace('\\', r'\\\\')
# Set preview client as most of the patchable fields are available in preview api-version
client = cf_connected_cluster_prev_2022_10_01(cmd.cli_ctx, None)
# Patching the connected cluster ARM resource
arm_properties_unset = (tags is None and distribution is None and distribution_version is None and azure_hybrid_benefit is None)
if not arm_properties_unset:
patch_cc_response = update_connected_cluster_internal(client, resource_group_name, cluster_name, tags, distribution, distribution_version, azure_hybrid_benefit)
proxy_params_unset = (https_proxy == "" and http_proxy == "" and no_proxy == "" and proxy_cert == "" and not disable_proxy)
# Returning the ARM response if only AHB is being updated
arm_properties_only_ahb_set = (tags is None and distribution is None and distribution_version is None and azure_hybrid_benefit is not None)
if proxy_params_unset and auto_upgrade is None and container_log_path is None and arm_properties_only_ahb_set:
return patch_cc_response
if proxy_params_unset and not auto_upgrade and arm_properties_unset and not container_log_path:
raise RequiredArgumentMissingError(consts.No_Param_Error)
if (https_proxy or http_proxy or no_proxy) and disable_proxy:
raise MutuallyExclusiveArgumentError(consts.EnableProxy_Conflict_Error)
# Checking whether optional extra values file has been provided.
values_file_provided, values_file = utils.get_values_file()
# Validate the helm environment file for Dogfood.
dp_endpoint_dogfood = None
release_train_dogfood = None
if cmd.cli_ctx.cloud.endpoints.resource_manager == consts.Dogfood_RMEndpoint:
dp_endpoint_dogfood, release_train_dogfood = validate_env_file_dogfood(values_file, values_file_provided)
# Loading the kubeconfig file in kubernetes client configuration
load_kube_config(kube_config, kube_context)
# Checking the connection to kubernetes cluster.
# This check was added to avoid large timeouts when connecting to AAD Enabled AKS clusters
# if the user had not logged in.