code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
194
url
stringlengths
46
254
license
stringclasses
4 values
def check_is_postprocessing_required(self, mc: ManagedCluster) -> bool: """Helper function to check if postprocessing is required after sending a PUT request to create the cluster. :return: bool """ from azure.cli.command_modules.acs._consts import CONST_AZURE_KEYVAULT_SECRETS_PROVIDER_ADDON_NAME # some addons require post cluster creation role assigment monitoring_addon_enabled = self.context.get_intermediate("monitoring_addon_enabled", default_value=False) ingress_appgw_addon_enabled = self.context.get_intermediate("ingress_appgw_addon_enabled", default_value=False) virtual_node_addon_enabled = self.context.get_intermediate("virtual_node_addon_enabled", default_value=False) enable_managed_identity = check_is_msi_cluster(mc) attach_acr = self.context.get_attach_acr() keyvault_id = self.context.get_keyvault_id() enable_azure_keyvault_secrets_provider_addon = self.context.get_enable_kv() or ( mc.addon_profiles and mc.addon_profiles.get(CONST_AZURE_KEYVAULT_SECRETS_PROVIDER_ADDON_NAME) and mc.addon_profiles[CONST_AZURE_KEYVAULT_SECRETS_PROVIDER_ADDON_NAME].enabled) enable_azure_container_storage = self.context.get_intermediate( "enable_azure_container_storage", default_value=False ) disable_azure_container_storage = self.context.get_intermediate( "disable_azure_container_storage", default_value=False ) # pylint: disable=too-many-boolean-expressions if ( monitoring_addon_enabled or ingress_appgw_addon_enabled or virtual_node_addon_enabled or (enable_managed_identity and attach_acr) or (keyvault_id and enable_azure_keyvault_secrets_provider_addon) or (enable_azure_container_storage or disable_azure_container_storage) ): return True return False
Helper function to check if postprocessing is required after sending a PUT request to create the cluster. :return: bool
check_is_postprocessing_required
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/managed_cluster_decorator.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/managed_cluster_decorator.py
MIT
def immediate_processing_after_request(self, mc: ManagedCluster) -> None: """Immediate processing performed when the cluster has not finished creating after a PUT request to the cluster has been sent. :return: None """ return
Immediate processing performed when the cluster has not finished creating after a PUT request to the cluster has been sent. :return: None
immediate_processing_after_request
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/managed_cluster_decorator.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/managed_cluster_decorator.py
MIT
def postprocessing_after_mc_created(self, cluster: ManagedCluster) -> None: """Postprocessing performed after the cluster is created. :return: None """ # monitoring addon monitoring_addon_enabled = self.context.get_intermediate("monitoring_addon_enabled", default_value=False) if monitoring_addon_enabled: enable_msi_auth_for_monitoring = self.context.get_enable_msi_auth_for_monitoring() if not enable_msi_auth_for_monitoring: # add cluster spn/msi Monitoring Metrics Publisher role assignment to publish metrics to MDM # mdm metrics is supported only in azure public cloud, so add the role assignment only in this cloud cloud_name = self.cmd.cli_ctx.cloud.name if cloud_name.lower() == "azurecloud": from azure.mgmt.core.tools import resource_id cluster_resource_id = resource_id( subscription=self.context.get_subscription_id(), resource_group=self.context.get_resource_group_name(), namespace="Microsoft.ContainerService", type="managedClusters", name=self.context.get_name(), ) self.context.external_functions.add_monitoring_role_assignment( cluster, cluster_resource_id, self.cmd ) elif ( self.context.raw_param.get("enable_addons") is not None ): # Create the DCR Association here addon_consts = self.context.get_addon_consts() CONST_MONITORING_ADDON_NAME = addon_consts.get("CONST_MONITORING_ADDON_NAME") self.context.external_functions.ensure_container_insights_for_monitoring( self.cmd, cluster.addon_profiles[CONST_MONITORING_ADDON_NAME], self.context.get_subscription_id(), self.context.get_resource_group_name(), self.context.get_name(), self.context.get_location(), remove_monitoring=False, aad_route=self.context.get_enable_msi_auth_for_monitoring(), create_dcr=False, create_dcra=True, enable_syslog=self.context.get_enable_syslog(), data_collection_settings=self.context.get_data_collection_settings(), is_private_cluster=self.context.get_enable_private_cluster(), ampls_resource_id=self.context.get_ampls_resource_id(), enable_high_log_scale_mode=self.context.get_enable_high_log_scale_mode(), ) # ingress appgw addon ingress_appgw_addon_enabled = self.context.get_intermediate("ingress_appgw_addon_enabled", default_value=False) if ingress_appgw_addon_enabled: self.context.external_functions.add_ingress_appgw_addon_role_assignment(cluster, self.cmd) # virtual node addon virtual_node_addon_enabled = self.context.get_intermediate("virtual_node_addon_enabled", default_value=False) if virtual_node_addon_enabled: self.context.external_functions.add_virtual_node_role_assignment( self.cmd, cluster, self.context.get_vnet_subnet_id() ) # attach acr enable_managed_identity = check_is_msi_cluster(cluster) attach_acr = self.context.get_attach_acr() if enable_managed_identity and attach_acr: # Attach ACR to cluster enabled managed identity if cluster.identity_profile is None or cluster.identity_profile["kubeletidentity"] is None: logger.warning( "Your cluster is successfully created, but we failed to attach " "acr to it, you can manually grant permission to the identity " "named <ClUSTER_NAME>-agentpool in MC_ resource group to give " "it permission to pull from ACR." ) else: kubelet_identity_object_id = cluster.identity_profile["kubeletidentity"].object_id self.context.external_functions.ensure_aks_acr( self.cmd, assignee=kubelet_identity_object_id, acr_name_or_id=attach_acr, subscription_id=self.context.get_subscription_id(), is_service_principal=False, ) enable_azure_container_storage = self.context.get_intermediate("enable_azure_container_storage") disable_azure_container_storage = self.context.get_intermediate("disable_azure_container_storage") is_extension_installed = self.context.get_intermediate("is_extension_installed") is_azureDisk_enabled = self.context.get_intermediate("is_azureDisk_enabled") is_elasticSan_enabled = self.context.get_intermediate("is_elasticSan_enabled") is_ephemeralDisk_localssd_enabled = self.context.get_intermediate("is_ephemeralDisk_localssd_enabled") is_ephemeralDisk_nvme_enabled = self.context.get_intermediate("is_ephemeralDisk_nvme_enabled") current_core_value = self.context.get_intermediate("current_core_value") existing_ephemeral_disk_volume_type = self.context.get_intermediate("existing_ephemeral_disk_volume_type") existing_ephemeral_nvme_perf_tier = self.context.get_intermediate("current_ephemeral_nvme_perf_tier") pool_option = self.context.raw_param.get("storage_pool_option") # enable azure container storage if enable_azure_container_storage: if cluster.identity_profile is None or cluster.identity_profile["kubeletidentity"] is None: logger.warning( "Unexpected error getting kubelet's identity for the cluster." "Unable to perform azure container storage operation." ) return pool_name = self.context.raw_param.get("storage_pool_name") pool_type = self.context.raw_param.get("enable_azure_container_storage") pool_sku = self.context.raw_param.get("storage_pool_sku") pool_size = self.context.raw_param.get("storage_pool_size") nodepool_list = self.context.get_intermediate("azure_container_storage_nodepools") ephemeral_disk_volume_type = self.context.raw_param.get("ephemeral_disk_volume_type") ephemeral_disk_nvme_perf_tier = self.context.raw_param.get("ephemeral_disk_nvme_perf_tier") kubelet_identity_object_id = cluster.identity_profile["kubeletidentity"].object_id acstor_nodepool_skus = [] for agentpool_profile in cluster.agent_pool_profiles: if agentpool_profile.name in nodepool_list: acstor_nodepool_skus.append(agentpool_profile.vm_size) self.context.external_functions.perform_enable_azure_container_storage( self.cmd, self.context.get_subscription_id(), self.context.get_resource_group_name(), self.context.get_name(), self.context.get_node_resource_group(), kubelet_identity_object_id, pool_name, pool_type, pool_size, pool_sku, pool_option, acstor_nodepool_skus, ephemeral_disk_volume_type, ephemeral_disk_nvme_perf_tier, False, existing_ephemeral_disk_volume_type, existing_ephemeral_nvme_perf_tier, is_extension_installed, is_azureDisk_enabled, is_elasticSan_enabled, is_ephemeralDisk_localssd_enabled, is_ephemeralDisk_nvme_enabled, current_core_value, ) # disable azure container storage if disable_azure_container_storage: pool_type = self.context.raw_param.get("disable_azure_container_storage") kubelet_identity_object_id = cluster.identity_profile["kubeletidentity"].object_id pre_disable_validate = self.context.get_intermediate("pre_disable_validate_azure_container_storage") self.context.external_functions.perform_disable_azure_container_storage( self.cmd, self.context.get_subscription_id(), self.context.get_resource_group_name(), self.context.get_name(), self.context.get_node_resource_group(), kubelet_identity_object_id, pre_disable_validate, pool_type, pool_option, is_elasticSan_enabled, is_azureDisk_enabled, is_ephemeralDisk_localssd_enabled, is_ephemeralDisk_nvme_enabled, current_core_value, existing_ephemeral_disk_volume_type, existing_ephemeral_nvme_perf_tier, ) # attach keyvault to app routing addon from azure.cli.command_modules.keyvault.custom import set_policy from azure.cli.command_modules.acs._client_factory import get_keyvault_client from azure.cli.command_modules.acs._consts import CONST_AZURE_KEYVAULT_SECRETS_PROVIDER_ADDON_NAME keyvault_id = self.context.get_keyvault_id() enable_azure_keyvault_secrets_provider_addon = ( self.context.get_enable_kv() or (cluster.addon_profiles and cluster.addon_profiles.get(CONST_AZURE_KEYVAULT_SECRETS_PROVIDER_ADDON_NAME) and cluster.addon_profiles[CONST_AZURE_KEYVAULT_SECRETS_PROVIDER_ADDON_NAME].enabled) ) logger.warning("keyvaultid: %s, enable_kv: %s", keyvault_id, enable_azure_keyvault_secrets_provider_addon) if keyvault_id: if enable_azure_keyvault_secrets_provider_addon: if cluster.ingress_profile and \ cluster.ingress_profile.web_app_routing and \ cluster.ingress_profile.web_app_routing.enabled: if not is_valid_resource_id(keyvault_id): raise InvalidArgumentValueError("Please provide a valid keyvault ID") self.cmd.command_kwargs['operation_group'] = 'vaults' keyvault_params = parse_resource_id(keyvault_id) keyvault_subscription = keyvault_params['subscription'] keyvault_name = keyvault_params['name'] keyvault_rg = keyvault_params['resource_group'] keyvault_client = get_keyvault_client(self.cmd.cli_ctx, subscription_id=keyvault_subscription) keyvault = keyvault_client.get(resource_group_name=keyvault_rg, vault_name=keyvault_name) managed_identity_object_id = cluster.ingress_profile.web_app_routing.identity.object_id is_service_principal = False try: if keyvault.properties.enable_rbac_authorization: if not self.context.external_functions.add_role_assignment( self.cmd, "Key Vault Secrets User", managed_identity_object_id, is_service_principal, scope=keyvault_id, ): logger.warning( "Could not create a role assignment for App Routing. " "Are you an Owner on this subscription?" ) else: keyvault = set_policy( self.cmd, keyvault_client, keyvault_rg, keyvault_name, object_id=managed_identity_object_id, secret_permissions=["Get"], certificate_permissions=["Get"], ) except Exception as ex: raise CLIError('Error in granting keyvault permissions to managed identity.\n') from ex else: raise CLIError('App Routing must be enabled to attach keyvault.\n') else: raise CLIError('Keyvault secrets provider addon must be enabled to attach keyvault.\n')
Postprocessing performed after the cluster is created. :return: None
postprocessing_after_mc_created
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/managed_cluster_decorator.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/managed_cluster_decorator.py
MIT
def update_mc(self, mc: ManagedCluster) -> ManagedCluster: """Send request to update the existing managed cluster. :return: the ManagedCluster object """ self._ensure_mc(mc) return self.put_mc(mc)
Send request to update the existing managed cluster. :return: the ManagedCluster object
update_mc
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/managed_cluster_decorator.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/managed_cluster_decorator.py
MIT
def get_k8s_upgrades_completion_list(cmd, prefix, namespace, **kwargs): # pylint: disable=unused-argument """Return Kubernetes versions available for upgrading an existing cluster.""" resource_group = getattr(namespace, 'resource_group_name', None) name = getattr(namespace, 'name', None) return get_k8s_upgrades(cmd.cli_ctx, resource_group, name) if resource_group and name else None
Return Kubernetes versions available for upgrading an existing cluster.
get_k8s_upgrades_completion_list
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_completers.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_completers.py
MIT
def get_k8s_versions_completion_list(cmd, prefix, namespace, **kwargs): # pylint: disable=unused-argument """Return Kubernetes versions available for provisioning a new cluster.""" location = _get_location(cmd.cli_ctx, namespace) return get_k8s_versions(cmd.cli_ctx, location) if location else None
Return Kubernetes versions available for provisioning a new cluster.
get_k8s_versions_completion_list
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_completers.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_completers.py
MIT
def get_k8s_versions(cli_ctx, location): """Return a list of Kubernetes versions available for a new cluster.""" from azure.cli.command_modules.acs._client_factory import cf_managed_clusters from jmespath import search results = cf_managed_clusters(cli_ctx).list_kubernetes_versions(location).as_dict() # Flatten all the "orchestrator_version" fields into one array return search("values[*].patchVersions.keys(@)[]", results)
Return a list of Kubernetes versions available for a new cluster.
get_k8s_versions
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_completers.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_completers.py
MIT
def get_vm_size_completion_list(cmd, prefix, namespace, **kwargs): # pylint: disable=unused-argument """Return the intersection of the VM sizes allowed by the ACS SDK with those returned by the Compute Service.""" from azure.mgmt.containerservice.models import ContainerServiceVMSizeTypes location = _get_location(cmd.cli_ctx, namespace) result = get_vm_sizes(cmd.cli_ctx, location) return set(r.name for r in result) & set(c.value for c in ContainerServiceVMSizeTypes)
Return the intersection of the VM sizes allowed by the ACS SDK with those returned by the Compute Service.
get_vm_size_completion_list
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_completers.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_completers.py
MIT
def _get_location(cli_ctx, namespace): """ Return an Azure location by using an explicit `--location` argument, then by `--resource-group`, and finally by the subscription if neither argument was provided. """ location = None if getattr(namespace, 'location', None): location = namespace.location elif getattr(namespace, 'resource_group_name', None): location = _get_location_from_resource_group(cli_ctx, namespace.resource_group_name) if not location: location = get_one_of_subscription_locations(cli_ctx) return location
Return an Azure location by using an explicit `--location` argument, then by `--resource-group`, and finally by the subscription if neither argument was provided.
_get_location
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_completers.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_completers.py
MIT
def validate_k8s_version(namespace): """Validates a string as a possible Kubernetes version. An empty string is also valid, which tells the server to use its default version.""" if namespace.kubernetes_version: k8s_release_regex = re.compile(r'^[v|V]?(\d+\.\d+(?:\.\d+)?)$') found = k8s_release_regex.findall(namespace.kubernetes_version) if found: namespace.kubernetes_version = found[0] else: raise CLIError('--kubernetes-version should be the full version number or major.minor version number, ' 'such as "1.7.12" or "1.7"')
Validates a string as a possible Kubernetes version. An empty string is also valid, which tells the server to use its default version.
validate_k8s_version
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def _validate_nodepool_name(nodepool_name): """Validates a nodepool name to be at most 12 characters, alphanumeric only.""" if nodepool_name != "": if len(nodepool_name) > 12: raise InvalidArgumentValueError('--nodepool-name can contain at most 12 characters') if not nodepool_name.isalnum(): raise InvalidArgumentValueError('--nodepool-name should contain only alphanumeric characters')
Validates a nodepool name to be at most 12 characters, alphanumeric only.
_validate_nodepool_name
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_nodepool_name(namespace): """Validates a nodepool name to be at most 12 characters, alphanumeric only.""" _validate_nodepool_name(namespace.nodepool_name)
Validates a nodepool name to be at most 12 characters, alphanumeric only.
validate_nodepool_name
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_agent_pool_name(namespace): """Validates a nodepool name to be at most 12 characters, alphanumeric only.""" _validate_nodepool_name(namespace.agent_pool_name)
Validates a nodepool name to be at most 12 characters, alphanumeric only.
validate_agent_pool_name
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_kubectl_version(namespace): """Validates a string as a possible Kubernetes version.""" k8s_release_regex = re.compile(r'^[v|V]?(\d+\.\d+\.\d+.*|latest)$') found = k8s_release_regex.findall(namespace.client_version) if found: namespace.client_version = found[0] else: raise CLIError('--client-version should be the full version number ' '(such as "1.11.8" or "1.12.6") or "latest"')
Validates a string as a possible Kubernetes version.
validate_kubectl_version
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_kubelogin_version(namespace): """Validates a string as a possible kubelogin version.""" kubelogin_regex = re.compile(r'^[v|V]?(\d+\.\d+\.\d+.*|latest)$') found = kubelogin_regex.findall(namespace.kubelogin_version) if found: namespace.kubelogin_version = found[0] else: raise CLIError('--kubelogin-version should be the full version number ' '(such as "0.0.4") or "latest"')
Validates a string as a possible kubelogin version.
validate_kubelogin_version
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_linux_host_name(namespace): """Validates a string as a legal host name component. This validation will also occur server-side in the ARM API, but that may take a minute or two before the user sees it. So it's more user-friendly to validate in the CLI pre-flight. """ # https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address rfc1123_regex = re.compile(r'^[a-zA-Z0-9]$|^[a-zA-Z0-9][-_a-zA-Z0-9]{0,61}[a-zA-Z0-9]$') # pylint:disable=line-too-long found = rfc1123_regex.findall(namespace.name) if not found: raise InvalidArgumentValueError('--name cannot exceed 63 characters and can only contain ' 'letters, numbers, underscores (_) or dashes (-).')
Validates a string as a legal host name component. This validation will also occur server-side in the ARM API, but that may take a minute or two before the user sees it. So it's more user-friendly to validate in the CLI pre-flight.
validate_linux_host_name
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_snapshot_name(namespace): """Validates a nodepool snapshot name to be alphanumeric and dashes.""" rfc1123_regex = re.compile(r'^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$') # pylint:disable=line-too-long found = rfc1123_regex.findall(namespace.snapshot_name) if not found: raise InvalidArgumentValueError('--name cannot exceed 63 characters and can only contain ' 'letters, numbers, or dashes (-).')
Validates a nodepool snapshot name to be alphanumeric and dashes.
validate_snapshot_name
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_vm_set_type(namespace): """Validates the vm set type string.""" if namespace.vm_set_type is not None: if namespace.vm_set_type == '': return if namespace.vm_set_type.lower() != "availabilityset" and \ namespace.vm_set_type.lower() != "virtualmachinescalesets": raise CLIError("--vm-set-type can only be VirtualMachineScaleSets or AvailabilitySet")
Validates the vm set type string.
validate_vm_set_type
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_load_balancer_sku(namespace): """Validates the load balancer sku string.""" if namespace.load_balancer_sku is not None: if namespace.load_balancer_sku == '': return if namespace.load_balancer_sku.lower() != "basic" and namespace.load_balancer_sku.lower() != "standard": raise CLIError("--load-balancer-sku can only be standard or basic")
Validates the load balancer sku string.
validate_load_balancer_sku
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_sku_tier(namespace): """Validates the sku tier string.""" if namespace.tier is not None: if namespace.tier == '': return if namespace.tier.lower() not in ( CONST_MANAGED_CLUSTER_SKU_TIER_FREE, CONST_MANAGED_CLUSTER_SKU_TIER_STANDARD, CONST_MANAGED_CLUSTER_SKU_TIER_PREMIUM): raise InvalidArgumentValueError("--tier can only be free, standard and premium")
Validates the sku tier string.
validate_sku_tier
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_load_balancer_outbound_ips(namespace): """validate load balancer profile outbound IP ids""" if namespace.load_balancer_outbound_ips is not None: ip_id_list = [x.strip() for x in namespace.load_balancer_outbound_ips.split(',')] if not all(ip_id_list): raise CLIError("--load-balancer-outbound-ips cannot contain whitespace")
validate load balancer profile outbound IP ids
validate_load_balancer_outbound_ips
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_load_balancer_outbound_ip_prefixes(namespace): """validate load balancer profile outbound IP prefix ids""" if namespace.load_balancer_outbound_ip_prefixes is not None: ip_prefix_id_list = [x.strip() for x in namespace.load_balancer_outbound_ip_prefixes.split(',')] if not all(ip_prefix_id_list): raise CLIError("--load-balancer-outbound-ip-prefixes cannot contain whitespace")
validate load balancer profile outbound IP prefix ids
validate_load_balancer_outbound_ip_prefixes
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_load_balancer_outbound_ports(namespace): """validate load balancer profile outbound allocated ports""" if namespace.load_balancer_outbound_ports is not None: if namespace.load_balancer_outbound_ports % 8 != 0: raise CLIError("--load-balancer-allocated-ports must be a multiple of 8") if namespace.load_balancer_outbound_ports < 0 or namespace.load_balancer_outbound_ports > 64000: raise CLIError("--load-balancer-allocated-ports must be in the range [0,64000]")
validate load balancer profile outbound allocated ports
validate_load_balancer_outbound_ports
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_load_balancer_idle_timeout(namespace): """validate load balancer profile idle timeout""" if namespace.load_balancer_idle_timeout is not None: if namespace.load_balancer_idle_timeout < 4 or namespace.load_balancer_idle_timeout > 100: raise CLIError("--load-balancer-idle-timeout must be in the range [4,100]")
validate load balancer profile idle timeout
validate_load_balancer_idle_timeout
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_network_policy(namespace): """validate network policy to be in lowercase""" if namespace.network_policy is not None and namespace.network_policy.islower() is False: raise InvalidArgumentValueError("--network-policy should be provided in lowercase")
validate network policy to be in lowercase
validate_network_policy
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_nat_gateway_managed_outbound_ip_count(namespace): """validate NAT gateway profile managed outbound IP count""" if namespace.nat_gateway_managed_outbound_ip_count is not None: if namespace.nat_gateway_managed_outbound_ip_count < 1 or namespace.nat_gateway_managed_outbound_ip_count > 16: raise InvalidArgumentValueError("--nat-gateway-managed-outbound-ip-count must be in the range [1,16]")
validate NAT gateway profile managed outbound IP count
validate_nat_gateway_managed_outbound_ip_count
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_nat_gateway_idle_timeout(namespace): """validate NAT gateway profile idle timeout""" if namespace.nat_gateway_idle_timeout is not None: if namespace.nat_gateway_idle_timeout < 4 or namespace.nat_gateway_idle_timeout > 120: raise InvalidArgumentValueError("--nat-gateway-idle-timeout must be in the range [4,120]")
validate NAT gateway profile idle timeout
validate_nat_gateway_idle_timeout
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_nodes_count(namespace): """Validates that min_count and max_count is set between 0-1000""" if namespace.min_count is not None: if namespace.min_count < 0 or namespace.min_count > 1000: raise CLIError('--min-count must be in the range [0,1000]') if namespace.max_count is not None: if namespace.max_count < 0 or namespace.max_count > 1000: raise CLIError('--max-count must be in the range [0,1000]')
Validates that min_count and max_count is set between 0-1000
validate_nodes_count
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_nodepool_taints(namespace): """Validates that provided node labels is a valid format""" if hasattr(namespace, 'nodepool_taints'): taintsStr = namespace.nodepool_taints else: taintsStr = namespace.node_taints if taintsStr is None or taintsStr == '': return for taint in taintsStr.split(','): validate_taint(taint)
Validates that provided node labels is a valid format
validate_nodepool_taints
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_taint(taint): """Validates that provided taint is a valid format""" regex = re.compile(r"^[a-zA-Z\d][\w\-\.\/]{0,252}=[a-zA-Z\d][\w\-\.]{0,62}:(NoSchedule|PreferNoSchedule|NoExecute)$") # pylint: disable=line-too-long if taint == "": return found = regex.findall(taint) if not found: raise ArgumentUsageError('Invalid node taint: %s' % taint)
Validates that provided taint is a valid format
validate_taint
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_priority(namespace): """Validates the node pool priority string.""" if namespace.priority is not None: if namespace.priority == '': return if namespace.priority != "Spot" and \ namespace.priority != "Regular": raise CLIError("--priority can only be Spot or Regular")
Validates the node pool priority string.
validate_priority
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_eviction_policy(namespace): """Validates the node pool priority string.""" if namespace.eviction_policy is not None: if namespace.eviction_policy == '': return if namespace.eviction_policy != "Delete" and \ namespace.eviction_policy != "Deallocate": raise CLIError("--eviction-policy can only be Delete or Deallocate")
Validates the node pool priority string.
validate_eviction_policy
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_spot_max_price(namespace): """Validates the spot node pool max price.""" if not isnan(namespace.spot_max_price): if namespace.priority != "Spot": raise CLIError("--spot_max_price can only be set when --priority is Spot") if len(str(namespace.spot_max_price).split(".")) > 1 and len(str(namespace.spot_max_price).split(".")[1]) > 5: raise CLIError("--spot_max_price can only include up to 5 decimal places") if namespace.spot_max_price <= 0 and not isclose(namespace.spot_max_price, -1.0, rel_tol=1e-06): raise CLIError( "--spot_max_price can only be any decimal value greater than zero, or -1 which indicates " "default price to be up-to on-demand")
Validates the spot node pool max price.
validate_spot_max_price
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_nodepool_tags(ns): """ Extracts multiple space-separated tags in key[=value] format """ if isinstance(ns.nodepool_tags, list): tags_dict = {} for item in ns.nodepool_tags: tags_dict.update(validate_tag(item)) ns.nodepool_tags = tags_dict
Extracts multiple space-separated tags in key[=value] format
validate_nodepool_tags
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_nodepool_labels(namespace): """Validates that provided node labels is a valid format""" if hasattr(namespace, 'nodepool_labels'): labels = namespace.nodepool_labels else: labels = namespace.labels if labels is None: return if isinstance(labels, list): labels_dict = {} for item in labels: labels_dict.update(validate_label(item)) after_validation_labels = labels_dict else: after_validation_labels = validate_label(labels) if hasattr(namespace, 'nodepool_labels'): namespace.nodepool_labels = after_validation_labels else: namespace.labels = after_validation_labels
Validates that provided node labels is a valid format
validate_nodepool_labels
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_label(label): """Validates that provided label is a valid format""" prefix_regex = re.compile(r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$") name_regex = re.compile(r"^([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]$") value_regex = re.compile(r"^(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])?$") if label == "": return {} kv = label.split('=') if len(kv) != 2: raise CLIError("Invalid label: %s. Label definition must be of format name=value." % label) name_parts = kv[0].split('/') if len(name_parts) == 1: name = name_parts[0] elif len(name_parts) == 2: prefix = name_parts[0] if not prefix or len(prefix) > 253: raise CLIError("Invalid label: %s. Label prefix can't be empty or more than 253 chars." % label) if not prefix_regex.match(prefix): raise CLIError("Invalid label: %s. Prefix part a DNS-1123 label must consist of lower case alphanumeric " "characters or '-', and must start and end with an alphanumeric character" % label) name = name_parts[1] else: raise CLIError("Invalid label: %s. A qualified name must consist of alphanumeric characters, '-', '_' " "or '.', and must start and end with an alphanumeric character (e.g. 'MyName', or " "'my.name', or '123-abc') with an optional DNS subdomain prefix and '/' " "(e.g. 'example.com/MyName')" % label) # validate label name if not name or len(name) > 63: raise CLIError("Invalid label: %s. Label name can't be empty or more than 63 chars." % label) if not name_regex.match(name): raise CLIError("Invalid label: %s. A qualified name must consist of alphanumeric characters, '-', '_' " "or '.', and must start and end with an alphanumeric character (e.g. 'MyName', or " "'my.name', or '123-abc') with an optional DNS subdomain prefix and '/' (e.g. " "'example.com/MyName')" % label) # validate label value if len(kv[1]) > 63: raise CLIError("Invalid label: %s. Label must not be more than 63 chars." % label) if not value_regex.match(kv[1]): raise CLIError("Invalid label: %s. A valid label must be an empty string or consist of alphanumeric " "characters, '-', '_' or '.', and must start and end with an alphanumeric character" % label) return {kv[0]: kv[1]}
Validates that provided label is a valid format
validate_label
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_max_surge(namespace): """validates parameters like max surge are postive integers or percents. less strict than RP""" if namespace.max_surge is None: return int_or_percent = namespace.max_surge if int_or_percent.endswith('%'): int_or_percent = int_or_percent.rstrip('%') try: if int(int_or_percent) < 0: raise CLIError("--max-surge must be positive") except ValueError: raise CLIError("--max-surge should be an int or percentage")
validates parameters like max surge are postive integers or percents. less strict than RP
validate_max_surge
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def extract_comma_separated_string( raw_string, enable_strip=False, extract_kv=False, allow_empty_value=False, keep_none=False, default_value=None, allow_appending_values_to_same_key=False, ): """Extract comma-separated string. If enable_strip is specified, will remove leading and trailing whitespace before each operation on the string. If extract_kv is specified, will extract key value pairs from the string with "=" as the delimiter and this would return a dictionary, otherwise keep the entire string. Option allow_empty_value is valid since extract_kv is specified. When the number of string segments split by "=" is 1, the first segment is retained as the key and empty string would be set as its corresponding value without raising an exception. Option allow_appending_values_to_same_key is valid since extract_kv is specified. For the same key, the new value is appended to the existing value separated by commas. If keep_none is specified, will return None when input is None. Otherwise will return default_value if input is None or empty string. """ if raw_string is None: if keep_none: return None return default_value if enable_strip: raw_string = raw_string.strip() if raw_string == "": return default_value result = {} if extract_kv else [] for item in raw_string.split(","): if enable_strip: item = item.strip() if extract_kv: kv_list = item.split("=") if len(kv_list) in [1, 2]: key = kv_list[0] value = "" if len(kv_list) == 2: value = kv_list[1] if not allow_empty_value and (value == "" or value.isspace()): raise InvalidArgumentValueError( "Empty value not allowed. The value '{}' of key '{}' in '{}' is empty. Raw input '{}'.".format( value, key, item, raw_string ) ) if enable_strip: key = key.strip() value = value.strip() if allow_appending_values_to_same_key and key in result: value = "{},{}".format(result[key], value) result[key] = value else: raise InvalidArgumentValueError( "The format of '{}' in '{}' is incorrect, correct format should be " "'Key1=Value1,Key2=Value2'.".format( item, raw_string ) ) else: result.append(item) return result
Extract comma-separated string. If enable_strip is specified, will remove leading and trailing whitespace before each operation on the string. If extract_kv is specified, will extract key value pairs from the string with "=" as the delimiter and this would return a dictionary, otherwise keep the entire string. Option allow_empty_value is valid since extract_kv is specified. When the number of string segments split by "=" is 1, the first segment is retained as the key and empty string would be set as its corresponding value without raising an exception. Option allow_appending_values_to_same_key is valid since extract_kv is specified. For the same key, the new value is appended to the existing value separated by commas. If keep_none is specified, will return None when input is None. Otherwise will return default_value if input is None or empty string.
extract_comma_separated_string
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_registry_name(cmd, namespace): """Append login server endpoint suffix.""" registry = namespace.acr suffixes = cmd.cli_ctx.cloud.suffixes # Some clouds do not define 'acr_login_server_endpoint' (e.g. AzureGermanCloud) from azure.cli.core.cloud import CloudSuffixNotSetException try: acr_suffix = suffixes.acr_login_server_endpoint except CloudSuffixNotSetException: acr_suffix = None if registry and acr_suffix: pos = registry.find(acr_suffix) if pos == -1: logger.warning("The login server endpoint suffix '%s' is automatically appended.", acr_suffix) namespace.acr = registry + acr_suffix
Append login server endpoint suffix.
validate_registry_name
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_utc_offset(namespace): """Validates --utc-offset for aks maintenanceconfiguration add/update commands.""" if namespace.utc_offset is None: return # The regex here is used to match strings to the "+HH:MM" or "-HH:MM" time format. # The complete regex breakdown is as follows: # ^ matches the start of the string and $ matches to the end of the string, respectively. # [+-] match to either + or - # \d{2}:\d{2} will match to two digits followed by a colon and two digits. (example: +05:30 which is 5 hours and 30 minutes ahead or -12:00 which is 12 hours behind) utc_offset_regex = re.compile(r'^[+-]\d{2}:\d{2}$') found = utc_offset_regex.findall(namespace.utc_offset) if not found: raise InvalidArgumentValueError('--utc-offset must be in format: "+/-HH:mm". For example, "+05:30" and "-12:00".')
Validates --utc-offset for aks maintenanceconfiguration add/update commands.
validate_utc_offset
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_start_date(namespace): """Validates --start-date for aks maintenanceconfiguration add/update commands.""" if namespace.start_date is None: return # The regex here is used to match strings to the "yyyy-MM-dd" date format. # The complete regex breakdown is as follows: # ^ matches the start of the string and $ matches to the end of the string, respectively. # ^\d{4}-\d{2}-\d{2} will match four digits, followed by a -, two digits, followed by a -. (example: 2023-01-01 which is January 1st 2023) start_dt_regex = re.compile(r'^\d{4}-\d{2}-\d{2}$') found = start_dt_regex.findall(namespace.start_date) if not found: raise InvalidArgumentValueError('--start-date must be in format: "yyyy-MM-dd". For example, "2023-01-01".')
Validates --start-date for aks maintenanceconfiguration add/update commands.
validate_start_date
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_start_time(namespace): """Validates --start-time for aks maintenanceconfiguration add/update commands.""" if namespace.start_time is None: return # The regex here is used to match strings to the "HH:MM" or "HH:MM" time format. # The complete regex breakdown is as follows: # ^ matches the start of the string and $ matches to the end of the string, respectively. # \d{2}:\d{2} will match to two digits followed by a colon and two digits. (example: 09:30 which is 9 hours and 30 minutes or 17:00 which is 17 hours and 00 minutes) start_time_regex = re.compile(r'^\d{2}:\d{2}$') found = start_time_regex.findall(namespace.start_time) if not found: raise InvalidArgumentValueError('--start-time must be in format "HH:mm". For example, "09:30" and "17:00".')
Validates --start-time for aks maintenanceconfiguration add/update commands.
validate_start_time
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_azure_service_mesh_revision(namespace): """Validates the user provided revision parameter for azure service mesh commands.""" if namespace.revision is None: return revision = namespace.revision asm_revision_regex = re.compile(r'^asm-\d+-\d+$') found = asm_revision_regex.findall(revision) if not found: raise InvalidArgumentValueError(f"Revision {revision} is not supported by the service mesh add-on.")
Validates the user provided revision parameter for azure service mesh commands.
validate_azure_service_mesh_revision
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_disable_windows_outbound_nat(namespace): """Validates disable_windows_outbound_nat can only be used on Windows.""" if namespace.disable_windows_outbound_nat: if hasattr(namespace, 'os_type') and str(namespace.os_type).lower() != "windows": raise ArgumentUsageError( '--disable-windows-outbound-nat can only be set for Windows nodepools')
Validates disable_windows_outbound_nat can only be used on Windows.
validate_disable_windows_outbound_nat
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def validate_message_of_the_day(namespace): """Validates message of the day can only be used on Linux.""" if namespace.message_of_the_day is not None and namespace.message_of_the_day != "": if namespace.os_type is not None and namespace.os_type != "Linux": raise ArgumentUsageError( '--message-of-the-day can only be set for linux nodepools')
Validates message of the day can only be used on Linux.
validate_message_of_the_day
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_validators.py
MIT
def update_load_balancer_profile(managed_outbound_ip_count, managed_outbound_ipv6_count, outbound_ips, outbound_ip_prefixes, outbound_ports, idle_timeout, backend_pool_type, profile, models): """parse and update an existing load balancer profile""" if not is_load_balancer_profile_provided(managed_outbound_ip_count, managed_outbound_ipv6_count, outbound_ips, outbound_ip_prefixes, outbound_ports, backend_pool_type, idle_timeout): return profile if not profile: if isinstance(models, SimpleNamespace): ManagedClusterLoadBalancerProfile = models.ManagedClusterLoadBalancerProfile else: ManagedClusterLoadBalancerProfile = models.get("ManagedClusterLoadBalancerProfile") profile = ManagedClusterLoadBalancerProfile() return configure_load_balancer_profile(managed_outbound_ip_count, managed_outbound_ipv6_count, outbound_ips, outbound_ip_prefixes, outbound_ports, idle_timeout, backend_pool_type, profile, models)
parse and update an existing load balancer profile
update_load_balancer_profile
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_loadbalancer.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_loadbalancer.py
MIT
def create_load_balancer_profile(managed_outbound_ip_count, managed_outbound_ipv6_count, outbound_ips, outbound_ip_prefixes, outbound_ports, idle_timeout, backend_pool_type, models): """parse and build load balancer profile""" if not is_load_balancer_profile_provided(managed_outbound_ip_count, managed_outbound_ipv6_count, outbound_ips, outbound_ip_prefixes, outbound_ports, backend_pool_type, idle_timeout): return None if isinstance(models, SimpleNamespace): ManagedClusterLoadBalancerProfile = models.ManagedClusterLoadBalancerProfile else: ManagedClusterLoadBalancerProfile = models.get("ManagedClusterLoadBalancerProfile") profile = ManagedClusterLoadBalancerProfile() return configure_load_balancer_profile(managed_outbound_ip_count, managed_outbound_ipv6_count, outbound_ips, outbound_ip_prefixes, outbound_ports, idle_timeout, backend_pool_type, profile, models)
parse and build load balancer profile
create_load_balancer_profile
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_loadbalancer.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_loadbalancer.py
MIT
def configure_load_balancer_profile(managed_outbound_ip_count, managed_outbound_ipv6_count, outbound_ips, outbound_ip_prefixes, outbound_ports, idle_timeout, backend_pool_type, profile, models): """configure a load balancer with customer supplied values""" if any([managed_outbound_ip_count is not None, managed_outbound_ipv6_count is not None, outbound_ips, outbound_ip_prefixes]): outbound_ip_resources = _get_load_balancer_outbound_ips(outbound_ips, models) if outbound_ip_resources: if isinstance(models, SimpleNamespace): ManagedClusterLoadBalancerProfileOutboundIPs = models.ManagedClusterLoadBalancerProfileOutboundIPs else: ManagedClusterLoadBalancerProfileOutboundIPs = models.get( "ManagedClusterLoadBalancerProfileOutboundIPs" ) # ips -> i_ps due to track 2 naming issue profile.outbound_i_ps = ManagedClusterLoadBalancerProfileOutboundIPs( public_i_ps=outbound_ip_resources ) elif profile.outbound_i_ps is not None: profile.outbound_i_ps = None outbound_ip_prefix_resources = _get_load_balancer_outbound_ip_prefixes(outbound_ip_prefixes, models) if outbound_ip_prefix_resources: if isinstance(models, SimpleNamespace): ManagedClusterLoadBalancerProfileOutboundIPPrefixes = ( models.ManagedClusterLoadBalancerProfileOutboundIPPrefixes ) else: ManagedClusterLoadBalancerProfileOutboundIPPrefixes = models.get( "ManagedClusterLoadBalancerProfileOutboundIPPrefixes" ) profile.outbound_ip_prefixes = ManagedClusterLoadBalancerProfileOutboundIPPrefixes( public_ip_prefixes=outbound_ip_prefix_resources ) elif profile.outbound_ip_prefixes is not None: profile.outbound_ip_prefixes = None if managed_outbound_ip_count is not None or managed_outbound_ipv6_count is not None: if profile.managed_outbound_i_ps is None: if isinstance(models, SimpleNamespace): ManagedClusterLoadBalancerProfileManagedOutboundIPs = ( models.ManagedClusterLoadBalancerProfileManagedOutboundIPs ) else: ManagedClusterLoadBalancerProfileManagedOutboundIPs = models.get( "ManagedClusterLoadBalancerProfileManagedOutboundIPs" ) profile.managed_outbound_i_ps = ManagedClusterLoadBalancerProfileManagedOutboundIPs() if managed_outbound_ip_count is not None: profile.managed_outbound_i_ps.count = managed_outbound_ip_count if managed_outbound_ipv6_count is not None: profile.managed_outbound_i_ps.count_ipv6 = managed_outbound_ipv6_count elif profile.managed_outbound_i_ps is not None: profile.managed_outbound_i_ps = None if outbound_ports is not None: profile.allocated_outbound_ports = outbound_ports if idle_timeout: profile.idle_timeout_in_minutes = idle_timeout if backend_pool_type: profile.backend_pool_type = backend_pool_type return profile
configure a load balancer with customer supplied values
configure_load_balancer_profile
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_loadbalancer.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_loadbalancer.py
MIT
def _get_load_balancer_outbound_ips(load_balancer_outbound_ips, models): """parse load balancer profile outbound IP ids and return an array of references to the outbound IP resources""" load_balancer_outbound_ip_resources = None if isinstance(models, SimpleNamespace): ResourceReference = models.ResourceReference else: ResourceReference = models.get("ResourceReference") if load_balancer_outbound_ips is not None: if isinstance(load_balancer_outbound_ips, str): load_balancer_outbound_ip_resources = \ [ResourceReference(id=x.strip()) for x in load_balancer_outbound_ips.split(',')] else: load_balancer_outbound_ip_resources = load_balancer_outbound_ips return load_balancer_outbound_ip_resources
parse load balancer profile outbound IP ids and return an array of references to the outbound IP resources
_get_load_balancer_outbound_ips
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_loadbalancer.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_loadbalancer.py
MIT
def _get_load_balancer_outbound_ip_prefixes(load_balancer_outbound_ip_prefixes, models): """parse load balancer profile outbound IP prefix ids and return an array \ of references to the outbound IP prefix resources""" load_balancer_outbound_ip_prefix_resources = None if isinstance(models, SimpleNamespace): ResourceReference = models.ResourceReference else: ResourceReference = models.get("ResourceReference") if load_balancer_outbound_ip_prefixes: if isinstance(load_balancer_outbound_ip_prefixes, str): load_balancer_outbound_ip_prefix_resources = \ [ResourceReference(id=x.strip()) for x in load_balancer_outbound_ip_prefixes.split(',')] else: load_balancer_outbound_ip_prefix_resources = load_balancer_outbound_ip_prefixes return load_balancer_outbound_ip_prefix_resources
parse load balancer profile outbound IP prefix ids and return an array \ of references to the outbound IP prefix resources
_get_load_balancer_outbound_ip_prefixes
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_loadbalancer.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_loadbalancer.py
MIT
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: _urlopen_read(url) except URLError: time.sleep(1) break webbrowser.open_new_tab(url)
Waits for a bit then opens a URL. Useful for waiting for a proxy to come up, and then open the URL.
wait_then_open
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/custom.py
MIT
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()
Spawns a thread that waits for a bit then opens a URL.
wait_then_open_async
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/custom.py
MIT
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
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.
_remove_nulls
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/custom.py
MIT
def _print_or_merge_credentials(path, kubeconfig, overwrite_existing, context_name): """Merge an unencrypted kubeconfig into the file at the specified path, or print it to stdout if the path is "-". """ # Special case for printing to stdout if path == "-": print(kubeconfig) return # ensure that at least an empty ~/.kube/config exists directory = os.path.dirname(path) if directory and not os.path.exists(directory): try: os.makedirs(directory) except OSError as ex: if ex.errno != errno.EEXIST: raise if not os.path.exists(path): with os.fdopen(os.open(path, os.O_CREAT | os.O_WRONLY, 0o600), 'wt'): pass # merge the new kubeconfig into the existing one fd, temp_path = tempfile.mkstemp() additional_file = os.fdopen(fd, 'w+t') try: additional_file.write(kubeconfig) additional_file.flush() merge_kubernetes_configurations( path, temp_path, overwrite_existing, context_name) except yaml.YAMLError as ex: logger.warning( 'Failed to merge credentials to kube config file: %s', ex) finally: additional_file.close() os.remove(temp_path)
Merge an unencrypted kubeconfig into the file at the specified path, or print it to stdout if the path is "-".
_print_or_merge_credentials
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/custom.py
MIT
def k8s_install_kubectl(cmd, client_version='latest', install_location=None, source_url=None, arch=None): """ Install kubectl, a command-line interface for Kubernetes clusters. """ if not source_url: source_url = "https://dl.k8s.io/release" cloud_name = cmd.cli_ctx.cloud.name if cloud_name.lower() == 'azurechinacloud': source_url = 'https://mirror.azure.cn/kubernetes/kubectl' if client_version == 'latest': latest_version_url = source_url + '/stable.txt' logger.warning('No version specified, will get the latest version of kubectl from "%s"', latest_version_url) version = _urlopen_read(source_url + '/stable.txt') client_version = version.decode('UTF-8').strip() else: client_version = "v%s" % client_version file_url = '' system = platform.system() if arch is None: arch = get_arch_for_cli_binary() base_url = source_url + f"/{{}}/bin/{{}}/{arch}/{{}}" # ensure installation directory exists install_dir, cli = os.path.dirname( install_location), os.path.basename(install_location) if not os.path.exists(install_dir): os.makedirs(install_dir) if system == 'Windows': binary_name = 'kubectl.exe' file_url = base_url.format(client_version, 'windows', binary_name) elif system == 'Linux': binary_name = 'kubectl' file_url = base_url.format(client_version, 'linux', binary_name) elif system == 'Darwin': binary_name = 'kubectl' file_url = base_url.format(client_version, 'darwin', binary_name) else: raise UnknownError("Unsupported system '{}'.".format(system)) # validate install location validate_install_location(install_location, binary_name) logger.warning('Downloading client to "%s" from "%s"', install_location, file_url) try: _urlretrieve(file_url, install_location) os.chmod(install_location, os.stat(install_location).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) except OSError as ex: raise CLIError( 'Connection error while attempting to download client ({})'.format(ex)) if system == 'Windows': handle_windows_post_install(install_dir, cli) else: logger.warning('Please ensure that %s is in your search PATH, so the `%s` command can be found.', install_dir, cli)
Install kubectl, a command-line interface for Kubernetes clusters.
k8s_install_kubectl
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/custom.py
MIT
def k8s_install_kubelogin(cmd, client_version='latest', install_location=None, source_url=None, arch=None): """ Install kubelogin, a client-go credential (exec) plugin implementing azure authentication. """ cloud_name = cmd.cli_ctx.cloud.name if not source_url: source_url = 'https://github.com/Azure/kubelogin/releases/download' if cloud_name.lower() == 'azurechinacloud': source_url = 'https://mirror.azure.cn/kubernetes/kubelogin' if client_version == 'latest': latest_release_url = 'https://api.github.com/repos/Azure/kubelogin/releases/latest' if cloud_name.lower() == 'azurechinacloud': latest_release_url = 'https://mirror.azure.cn/kubernetes/kubelogin/latest' logger.warning('No version specified, will get the latest version of kubelogin from "%s"', latest_release_url) latest_release = _urlopen_read(latest_release_url) client_version = json.loads(latest_release)['tag_name'].strip() else: client_version = "v%s" % client_version base_url = source_url + '/{}/kubelogin.zip' file_url = base_url.format(client_version) # ensure installation directory exists install_dir, cli = os.path.dirname( install_location), os.path.basename(install_location) if not os.path.exists(install_dir): os.makedirs(install_dir) system = platform.system() if arch is None: arch = get_arch_for_cli_binary() if system == 'Windows': sub_dir, binary_name = 'windows_amd64', 'kubelogin.exe' elif system == 'Linux': sub_dir, binary_name = f'linux_{arch}', 'kubelogin' elif system == 'Darwin': sub_dir, binary_name = f'darwin_{arch}', 'kubelogin' else: raise UnknownError("Unsupported system '{}'.".format(system)) # validate install location validate_install_location(install_location, binary_name) with tempfile.TemporaryDirectory() as tmp_dir: try: download_path = os.path.join(tmp_dir, 'kubelogin.zip') logger.warning('Downloading client to "%s" from "%s"', download_path, file_url) _urlretrieve(file_url, download_path) except OSError as ex: raise CLIError( 'Connection error while attempting to download client ({})'.format(ex)) _unzip(download_path, tmp_dir) download_path = os.path.join(tmp_dir, 'bin', sub_dir, binary_name) logger.warning('Moving binary to "%s" from "%s"', install_location, download_path) shutil.move(download_path, install_location) os.chmod(install_location, os.stat(install_location).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) if system == 'Windows': handle_windows_post_install(install_dir, cli) else: logger.warning('Please ensure that %s is in your search PATH, so the `%s` command can be found.', install_dir, cli)
Install kubelogin, a client-go credential (exec) plugin implementing azure authentication.
k8s_install_kubelogin
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/custom.py
MIT
def aks_use_dev_spaces(cmd, client, name, resource_group_name, update=False, space_name=None, endpoint_type='Public', prompt=False): """ Use Azure Dev Spaces with a managed Kubernetes cluster. :param name: Name of the managed cluster. :type name: String :param resource_group_name: Name of resource group. You can configure the default group. \ Using 'az configure --defaults group=<name>'. :type resource_group_name: String :param update: Update to the latest Azure Dev Spaces client components. :type update: bool :param space_name: Name of the new or existing dev space to select. Defaults to an \ interactive selection experience. :type space_name: String :param endpoint_type: The endpoint type to be used for a Azure Dev Spaces controller. \ See https://aka.ms/azds-networking for more information. :type endpoint_type: String :param prompt: Do not prompt for confirmation. Requires --space. :type prompt: bool """ if _get_or_add_extension(cmd, DEV_SPACES_EXTENSION_NAME, DEV_SPACES_EXTENSION_MODULE, update): azext_custom = _get_azext_module( DEV_SPACES_EXTENSION_NAME, DEV_SPACES_EXTENSION_MODULE) try: azext_custom.ads_use_dev_spaces( name, resource_group_name, update, space_name, endpoint_type, prompt) except TypeError: raise CLIError( "Use '--update' option to get the latest Azure Dev Spaces client components.") except AttributeError as ae: raise CLIError(ae)
Use Azure Dev Spaces with a managed Kubernetes cluster. :param name: Name of the managed cluster. :type name: String :param resource_group_name: Name of resource group. You can configure the default group. \ Using 'az configure --defaults group=<name>'. :type resource_group_name: String :param update: Update to the latest Azure Dev Spaces client components. :type update: bool :param space_name: Name of the new or existing dev space to select. Defaults to an \ interactive selection experience. :type space_name: String :param endpoint_type: The endpoint type to be used for a Azure Dev Spaces controller. \ See https://aka.ms/azds-networking for more information. :type endpoint_type: String :param prompt: Do not prompt for confirmation. Requires --space. :type prompt: bool
aks_use_dev_spaces
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/custom.py
MIT
def aks_remove_dev_spaces(cmd, client, name, resource_group_name, prompt=False): """ Remove Azure Dev Spaces from a managed Kubernetes cluster. :param name: Name of the managed cluster. :type name: String :param resource_group_name: Name of resource group. You can configure the default group. \ Using 'az configure --defaults group=<name>'. :type resource_group_name: String :param prompt: Do not prompt for confirmation. :type prompt: bool """ if _get_or_add_extension(cmd, DEV_SPACES_EXTENSION_NAME, DEV_SPACES_EXTENSION_MODULE): azext_custom = _get_azext_module( DEV_SPACES_EXTENSION_NAME, DEV_SPACES_EXTENSION_MODULE) try: azext_custom.ads_remove_dev_spaces( name, resource_group_name, prompt) except AttributeError as ae: raise CLIError(ae)
Remove Azure Dev Spaces from a managed Kubernetes cluster. :param name: Name of the managed cluster. :type name: String :param resource_group_name: Name of resource group. You can configure the default group. \ Using 'az configure --defaults group=<name>'. :type resource_group_name: String :param prompt: Do not prompt for confirmation. :type prompt: bool
aks_remove_dev_spaces
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/custom.py
MIT
def validate_decorator_mode(decorator_mode) -> bool: """Check if decorator_mode is a value of enum type DecoratorMode. :return: bool """ return isinstance(decorator_mode, DecoratorMode) and decorator_mode in DecoratorMode
Check if decorator_mode is a value of enum type DecoratorMode. :return: bool
validate_decorator_mode
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/base_decorator.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/base_decorator.py
MIT
def model_module(self) -> ModuleType: """Load the module that stores all aks models. :return: the models module in SDK """ if self.__model_module is None: self.__model_module = self.__cmd.get_models( resource_type=self.resource_type, operation_group="managed_clusters", ).models return self.__model_module
Load the module that stores all aks models. :return: the models module in SDK
model_module
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/base_decorator.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/base_decorator.py
MIT
def models_dict(self) -> Dict[str, Type]: """Filter out aks models from the model module and store it as a dictionary with the model name-class as the key-value pair. :return: dictionary """ if self.__model_dict is None: self.__model_dict = {} for k, v in vars(self.model_module).items(): if isinstance(v, type): self.__model_dict[k] = v return self.__model_dict
Filter out aks models from the model module and store it as a dictionary with the model name-class as the key-value pair. :return: dictionary
models_dict
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/base_decorator.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/base_decorator.py
MIT
def __set_up_base_aks_models(self) -> None: """Expose all aks models as properties of the class. """ for model_name, model_class in self.models_dict.items(): setattr(self, model_name, model_class)
Expose all aks models as properties of the class.
__set_up_base_aks_models
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/base_decorator.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/base_decorator.py
MIT
def get_intermediate(self, variable_name: str, default_value: Any = None) -> Any: """Get the value of an intermediate by its name. Get the value from the intermediates dictionary with variable_name as the key. If variable_name does not exist, default_value will be returned. :return: Any """ if variable_name not in self.intermediates: logger.debug( "The intermediate '%s' does not exist. Return default value '%s'.", variable_name, default_value, ) intermediate_value = self.intermediates.get(variable_name, default_value) return intermediate_value
Get the value of an intermediate by its name. Get the value from the intermediates dictionary with variable_name as the key. If variable_name does not exist, default_value will be returned. :return: Any
get_intermediate
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/base_decorator.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/base_decorator.py
MIT
def set_intermediate( self, variable_name: str, value: Any, overwrite_exists: bool = False ) -> None: """Set the value of an intermediate by its name. In the case that the intermediate value already exists, if overwrite_exists is enabled, the value will be overwritten and the log will be output at the debug level, otherwise the value will not be overwritten and the log will be output at the warning level, which by default will be output to stderr and seen by user. :return: None """ if variable_name in self.intermediates: if overwrite_exists: msg = "The intermediate '{}' is overwritten. Original value: '{}', new value: '{}'.".format( variable_name, self.intermediates.get(variable_name), value ) logger.debug(msg) self.intermediates[variable_name] = value elif self.intermediates.get(variable_name) != value: msg = "The intermediate '{}' already exists, but overwrite is not enabled. " \ "Original value: '{}', candidate value: '{}'.".format( variable_name, self.intermediates.get(variable_name), value, ) # warning level log will be output to the console, which may cause confusion to users logger.warning(msg) else: self.intermediates[variable_name] = value
Set the value of an intermediate by its name. In the case that the intermediate value already exists, if overwrite_exists is enabled, the value will be overwritten and the log will be output at the debug level, otherwise the value will not be overwritten and the log will be output at the warning level, which by default will be output to stderr and seen by user. :return: None
set_intermediate
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/base_decorator.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/base_decorator.py
MIT
def remove_intermediate(self, variable_name: str) -> None: """Remove the value of an intermediate by its name. No exception will be raised if the intermediate does not exist. :return: None """ self.intermediates.pop(variable_name, None)
Remove the value of an intermediate by its name. No exception will be raised if the intermediate does not exist. :return: None
remove_intermediate
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/base_decorator.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/base_decorator.py
MIT
def __init__( self, cmd: AzCliCommand, client: ContainerServiceClient, ): """A basic controller that follows the decorator pattern, used to compose the ManagedCluster profile and send requests. Note: This is a base class and should not be used directly. """ self.cmd = cmd self.client = client
A basic controller that follows the decorator pattern, used to compose the ManagedCluster profile and send requests. Note: This is a base class and should not be used directly.
__init__
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/base_decorator.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/base_decorator.py
MIT
def format_parameter_name_to_option_name(parameter_name: str) -> str: """Convert a name in parameter format to option format. Underscores ("_") are used to connect the various parts of a parameter name, while hyphens ("-") are used to connect each part of an option name. Besides, the option name starts with double hyphens ("--"). :return: str """ option_name = "--" + parameter_name.replace("_", "-") return option_name
Convert a name in parameter format to option format. Underscores ("_") are used to connect the various parts of a parameter name, while hyphens ("-") are used to connect each part of an option name. Besides, the option name starts with double hyphens ("--"). :return: str
format_parameter_name_to_option_name
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_helpers.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_helpers.py
MIT
def safe_list_get(li: List, idx: int, default: Any = None) -> Any: """Get an element from a list without raising IndexError. Attempt to get the element with index idx from a list-like object li, and if the index is invalid (such as out of range), return default (whose default value is None). :return: an element of any type """ if isinstance(li, list): try: return li[idx] except IndexError: return default return None
Get an element from a list without raising IndexError. Attempt to get the element with index idx from a list-like object li, and if the index is invalid (such as out of range), return default (whose default value is None). :return: an element of any type
safe_list_get
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_helpers.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_helpers.py
MIT
def safe_lower(obj: Any) -> Any: """Return lowercase string if the provided obj is a string, otherwise return the object itself. :return: Any """ if isinstance(obj, str): return obj.lower() return obj
Return lowercase string if the provided obj is a string, otherwise return the object itself. :return: Any
safe_lower
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_helpers.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_helpers.py
MIT
def get_property_from_dict_or_object(obj, property_name) -> Any: """Get the value corresponding to the property name from a dictionary or object. Note: Would raise exception if the property does not exist. :return: Any """ if isinstance(obj, dict): return obj[property_name] return getattr(obj, property_name)
Get the value corresponding to the property name from a dictionary or object. Note: Would raise exception if the property does not exist. :return: Any
get_property_from_dict_or_object
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_helpers.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_helpers.py
MIT
def check_is_msi_cluster(mc: ManagedCluster) -> bool: """Check `mc` object to determine whether managed identity is enabled. :return: bool """ if mc and mc.identity and mc.identity.type is not None: identity_type = mc.identity.type.casefold() if identity_type in ("systemassigned", "userassigned"): return True return False
Check `mc` object to determine whether managed identity is enabled. :return: bool
check_is_msi_cluster
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_helpers.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_helpers.py
MIT
def check_is_private_cluster(mc: ManagedCluster) -> bool: """Check `mc` object to determine whether private cluster is enabled. :return: bool """ if mc and mc.api_server_access_profile: return bool(mc.api_server_access_profile.enable_private_cluster) return False
Check `mc` object to determine whether private cluster is enabled. :return: bool
check_is_private_cluster
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_helpers.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_helpers.py
MIT
def check_is_apiserver_vnet_integration_cluster(mc: ManagedCluster) -> bool: """Check `mc` object to determine whether apiserver vnet integration is enabled. Note: enableVnetIntegration is still in preview api so we use additional_properties here :return: bool """ if mc and mc.api_server_access_profile: additional_properties = mc.api_server_access_profile.additional_properties if 'enableVnetIntegration' in additional_properties: return additional_properties['enableVnetIntegration'] return False return False
Check `mc` object to determine whether apiserver vnet integration is enabled. Note: enableVnetIntegration is still in preview api so we use additional_properties here :return: bool
check_is_apiserver_vnet_integration_cluster
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_helpers.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_helpers.py
MIT
def check_is_private_link_cluster(mc: ManagedCluster) -> bool: """Check `mc` object to determine whether private link cluster is enabled. :return: bool """ return check_is_private_cluster(mc) and not check_is_apiserver_vnet_integration_cluster(mc)
Check `mc` object to determine whether private link cluster is enabled. :return: bool
check_is_private_link_cluster
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_helpers.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_helpers.py
MIT
def check_is_managed_aad_cluster(mc: ManagedCluster) -> bool: """Check `mc` object to determine whether managed aad is enabled. :return: bool """ if mc and mc.aad_profile is not None and mc.aad_profile.managed: return True return False
Check `mc` object to determine whether managed aad is enabled. :return: bool
check_is_managed_aad_cluster
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_helpers.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_helpers.py
MIT
def create_nat_gateway_profile(managed_outbound_ip_count, idle_timeout, models: SimpleNamespace): """parse and build NAT gateway profile""" if not is_nat_gateway_profile_provided(managed_outbound_ip_count, idle_timeout): return None profile = models.ManagedClusterNATGatewayProfile() return configure_nat_gateway_profile(managed_outbound_ip_count, idle_timeout, profile, models)
parse and build NAT gateway profile
create_nat_gateway_profile
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_natgateway.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_natgateway.py
MIT
def update_nat_gateway_profile(managed_outbound_ip_count, idle_timeout, profile, models: SimpleNamespace): """parse and update an existing NAT gateway profile""" if not is_nat_gateway_profile_provided(managed_outbound_ip_count, idle_timeout): return profile if not profile: profile = models.ManagedClusterNATGatewayProfile() return configure_nat_gateway_profile(managed_outbound_ip_count, idle_timeout, profile, models)
parse and update an existing NAT gateway profile
update_nat_gateway_profile
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_natgateway.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_natgateway.py
MIT
def configure_nat_gateway_profile(managed_outbound_ip_count, idle_timeout, profile, models: SimpleNamespace): """configure a NAT Gateway with customer supplied values""" if managed_outbound_ip_count is not None: ManagedClusterManagedOutboundIPProfile = models.ManagedClusterManagedOutboundIPProfile profile.managed_outbound_ip_profile = ManagedClusterManagedOutboundIPProfile( count=managed_outbound_ip_count ) if idle_timeout: profile.idle_timeout_in_minutes = idle_timeout return profile
configure a NAT Gateway with customer supplied values
configure_nat_gateway_profile
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_natgateway.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_natgateway.py
MIT
def get_resource_by_name(cli_ctx, resource_name, resource_type): """Returns the ARM resource in the current subscription with resource_name. :param str resource_name: The name of resource :param str resource_type: The type of resource """ result = get_resources_in_subscription(cli_ctx, resource_type) elements = [item for item in result if item.name.lower() == resource_name.lower()] if not elements: from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cli_ctx) message = "The resource with name '{}' and type '{}' could not be found".format( resource_name, resource_type) try: subscription = profile.get_subscription( cli_ctx.data['subscription_id']) raise CLIError( "{} in subscription '{} ({})'.".format(message, subscription['name'], subscription['id'])) except (KeyError, TypeError): raise CLIError( "{} in the current subscription.".format(message)) elif len(elements) == 1: return elements[0] else: raise CLIError( "More than one resources with type '{}' are found with name '{}'.".format( resource_type, resource_name))
Returns the ARM resource in the current subscription with resource_name. :param str resource_name: The name of resource :param str resource_type: The type of resource
get_resource_by_name
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_client_factory.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_client_factory.py
MIT
def aks_agentpool_show_table_format(result): """Format an agent pool as summary results for display with "-o table".""" return [_aks_agentpool_table_format(result)]
Format an agent pool as summary results for display with "-o table".
aks_agentpool_show_table_format
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_format.py
MIT
def aks_agentpool_list_table_format(results): """Format an agent pool list for display with "-o table".""" return [_aks_agentpool_table_format(r) for r in results]
Format an agent pool list for display with "-o table".
aks_agentpool_list_table_format
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_format.py
MIT
def aks_list_table_format(results): """"Format a list of managed clusters as summary results for display with "-o table".""" return [_aks_table_format(r) for r in results]
Format a list of managed clusters as summary results for display with "-o table".
aks_list_table_format
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_format.py
MIT
def aks_show_table_format(result): """Format a managed cluster as summary results for display with "-o table".""" return [_aks_table_format(result)]
Format a managed cluster as summary results for display with "-o table".
aks_show_table_format
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_format.py
MIT
def aks_upgrades_table_format(result): """Format get-upgrades results as a summary for display with "-o table".""" preview = {} def find_preview_versions(versions_bag): for upgrade in versions_bag.get('upgrades', []): if upgrade.get('isPreview', False): preview[upgrade['kubernetesVersion']] = True find_preview_versions(result.get('controlPlaneProfile', {})) # This expression assumes there is one node pool, and that the master and nodes upgrade in lockstep. parsed = compile_jmes("""{ name: name, resourceGroup: resourceGroup, masterVersion: controlPlaneProfile.kubernetesVersion || `unknown`, upgrades: controlPlaneProfile.upgrades[].kubernetesVersion || [`None available`] | sort_versions(@) | set_preview_array(@) | join(`, `, @) }""") # use ordered dicts so headers are predictable return parsed.search(result, Options(dict_cls=OrderedDict, custom_functions=_custom_functions(preview)))
Format get-upgrades results as a summary for display with "-o table".
aks_upgrades_table_format
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_format.py
MIT
def aks_versions_table_format(result): """Format get-versions results as a summary for display with "-o table".""" version_table = flatten_version_table(result.get("values", [])) parsed = compile_jmes("""[].{ kubernetesVersion: version, isPreview: isPreview, upgrades: upgrades || [`None available`] | sort_versions(@) | join(`, `, @), supportPlan: supportPlan | join(`, `, @) }""") # use ordered dicts so headers are predictable results = parsed.search(version_table, Options( dict_cls=OrderedDict, custom_functions=_custom_functions({}))) return sorted(results, key=lambda x: version_to_tuple(x.get("kubernetesVersion")), reverse=True)
Format get-versions results as a summary for display with "-o table".
aks_versions_table_format
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_format.py
MIT
def aks_list_nodepool_snapshot_table_format(results): """"Format a list of nodepool snapshots as summary results for display with "-o table".""" return [_aks_nodepool_snapshot_table_format(r) for r in results]
Format a list of nodepool snapshots as summary results for display with "-o table".
aks_list_nodepool_snapshot_table_format
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_format.py
MIT
def aks_show_nodepool_snapshot_table_format(result): """Format a nodepool snapshot as summary results for display with "-o table".""" return [_aks_nodepool_snapshot_table_format(result)]
Format a nodepool snapshot as summary results for display with "-o table".
aks_show_nodepool_snapshot_table_format
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_format.py
MIT
def version_to_tuple(version): """Removes preview suffix""" if version.endswith('(preview)'): version = version[:-len('(preview)')] return tuple(map(int, (version.split('.'))))
Removes preview suffix
version_to_tuple
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_format.py
MIT
def flatten_version_table(release_info): """Flattens version table""" flattened = [] for release in release_info: isPreview = release.get("isPreview", False) supportPlan = release.get("capabilities", {}).get("supportPlan", {}) for k, v in release.get("patchVersions", {}).items(): item = {"version": k, "upgrades": v.get("upgrades", []), "isPreview": isPreview, "supportPlan": supportPlan} flattened.append(item) return flattened
Flattens version table
flatten_version_table
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_format.py
MIT
def _func_sort_versions(self, versions): # pylint: disable=no-self-use """Custom JMESPath `sort_versions` function that sorts an array of strings as software versions.""" try: return sorted(versions, key=version_to_tuple) # if it wasn't sortable, return the input so the pipeline continues except (TypeError, ValueError): return versions
Custom JMESPath `sort_versions` function that sorts an array of strings as software versions.
_custom_functions._func_sort_versions
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_format.py
MIT
def _func_set_preview_array(self, versions): """Custom JMESPath `set_preview_array` function that suffixes preview version""" try: for i, _ in enumerate(versions): versions[i] = self._func_set_preview(versions[i]) return versions except (TypeError, ValueError): return versions
Custom JMESPath `set_preview_array` function that suffixes preview version
_custom_functions._func_set_preview_array
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_format.py
MIT
def _func_set_preview(self, version): # pylint: disable=no-self-use """Custom JMESPath `set_preview` function that suffixes preview version""" try: if preview_versions.get(version, False): return version + '(preview)' return version except (TypeError, ValueError): return version
Custom JMESPath `set_preview` function that suffixes preview version
_custom_functions._func_set_preview
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_format.py
MIT
def _custom_functions(preview_versions): class CustomFunctions(functions.Functions): # pylint: disable=too-few-public-methods @functions.signature({'types': ['array']}) def _func_sort_versions(self, versions): # pylint: disable=no-self-use """Custom JMESPath `sort_versions` function that sorts an array of strings as software versions.""" try: return sorted(versions, key=version_to_tuple) # if it wasn't sortable, return the input so the pipeline continues except (TypeError, ValueError): return versions @functions.signature({'types': ['array']}) def _func_set_preview_array(self, versions): """Custom JMESPath `set_preview_array` function that suffixes preview version""" try: for i, _ in enumerate(versions): versions[i] = self._func_set_preview(versions[i]) return versions except (TypeError, ValueError): return versions @functions.signature({'types': ['string']}) def _func_set_preview(self, version): # pylint: disable=no-self-use """Custom JMESPath `set_preview` function that suffixes preview version""" try: if preview_versions.get(version, False): return version + '(preview)' return version except (TypeError, ValueError): return version return CustomFunctions()
Custom JMESPath `sort_versions` function that sorts an array of strings as software versions.
_custom_functions
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_format.py
MIT
def aks_mesh_revisions_table_format(result): """Format a list of mesh revisions as summary results for display with "-o table". """ revision_table = flatten_mesh_revision_table(result['meshRevisions']) parsed = compile_jmes("""[].{ revision: revision, upgrades: upgrades || [`None available`] | sort_versions(@) | join(`, `, @), compatibleWith: compatibleWith_name, compatibleVersions: compatibleVersions || [`None available`] | sort_versions(@) | join(`, `, @) }""") # Use ordered dicts so headers are predictable results = parsed.search(revision_table, Options( dict_cls=OrderedDict, custom_functions=_custom_functions({}))) return results
Format a list of mesh revisions as summary results for display with "-o table".
aks_mesh_revisions_table_format
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_format.py
MIT
def flatten_mesh_revision_table(revision_info): """Flattens revision information""" flattened = [] for revision_data in revision_info: flattened.extend(_format_mesh_revision_entry(revision_data)) return flattened
Flattens revision information
flatten_mesh_revision_table
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_format.py
MIT
def aks_mesh_upgrades_table_format(result): """Format a list of mesh upgrades as summary results for display with "-o table". """ upgrades_table = _format_mesh_revision_entry(result) parsed = compile_jmes("""[].{ revision: revision, upgrades: upgrades || [`None available`] | sort_versions(@) | join(`, `, @), compatibleWith: compatibleWith_name, compatibleVersions: compatibleVersions || [`None available`] | sort_versions(@) | join(`, `, @) }""") # Use ordered dicts so headers are predictable results = parsed.search(upgrades_table, Options( dict_cls=OrderedDict, custom_functions=_custom_functions({}))) return results
Format a list of mesh upgrades as summary results for display with "-o table".
aks_mesh_upgrades_table_format
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/_format.py
MIT
def __choose_agentpool_model_by_agentpool_decorator_mode(self): """Choose the model reference for agentpool based on agentpool_decorator_mode. """ if self.agentpool_decorator_mode == AgentPoolDecoratorMode.MANAGED_CLUSTER: return self.ManagedClusterAgentPoolProfile return self.AgentPool
Choose the model reference for agentpool based on agentpool_decorator_mode.
__choose_agentpool_model_by_agentpool_decorator_mode
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/agentpool_decorator.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/agentpool_decorator.py
MIT
def attach_agentpool(self, agentpool: AgentPool) -> None: """Attach the AgentPool object to the context. The `agentpool` object is only allowed to be attached once, and attaching again will raise a CLIInternalError. :return: None """ if self.decorator_mode == DecoratorMode.UPDATE: self.attach_existing_agentpool(agentpool) if self.agentpool is None: self.agentpool = agentpool else: msg = "the same" if self.agentpool == agentpool else "different" raise CLIInternalError( "Attempting to attach the `agentpool` object again, the two objects are {}.".format( msg ) )
Attach the AgentPool object to the context. The `agentpool` object is only allowed to be attached once, and attaching again will raise a CLIInternalError. :return: None
attach_agentpool
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/agentpool_decorator.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/agentpool_decorator.py
MIT
def __validate_counts_in_autoscaler( self, node_count, enable_cluster_autoscaler, min_count, max_count, mode, decorator_mode, ) -> None: """Helper function to check the validity of serveral count-related parameters in autoscaler. On the premise that enable_cluster_autoscaler (in update mode, this could be update_cluster_autoscaler) is enabled, it will check whether both min_count and max_count are assigned, if not, raise the RequiredArgumentMissingError. If min_count is less than max_count, raise the InvalidArgumentValueError. Only in create mode it will check whether the value of node_count is between min_count and max_count, if not, raise the InvalidArgumentValueError. If enable_cluster_autoscaler (in update mode, this could be update_cluster_autoscaler) is not enabled, it will check whether any of min_count or max_count is assigned, if so, raise the RequiredArgumentMissingError. :return: None """ # validation if enable_cluster_autoscaler: if min_count is None or max_count is None: raise RequiredArgumentMissingError( "Please specify both min-count and max-count when --enable-cluster-autoscaler enabled" ) if min_count > max_count: raise InvalidArgumentValueError( "Value of min-count should be less than or equal to value of max-count" ) if decorator_mode == DecoratorMode.CREATE: if node_count < min_count or node_count > max_count: raise InvalidArgumentValueError( "node-count is not in the range of min-count and max-count" ) if mode == CONST_NODEPOOL_MODE_SYSTEM: if min_count < 1: raise InvalidArgumentValueError( "Value of min-count should be greater than or equal to 1 for System node pools" ) else: if min_count is not None or max_count is not None: option_name = "--enable-cluster-autoscaler" if decorator_mode == DecoratorMode.UPDATE: option_name += " or --update-cluster-autoscaler" raise RequiredArgumentMissingError( "min-count and max-count are required for {}, please use the flag".format( option_name ) )
Helper function to check the validity of serveral count-related parameters in autoscaler. On the premise that enable_cluster_autoscaler (in update mode, this could be update_cluster_autoscaler) is enabled, it will check whether both min_count and max_count are assigned, if not, raise the RequiredArgumentMissingError. If min_count is less than max_count, raise the InvalidArgumentValueError. Only in create mode it will check whether the value of node_count is between min_count and max_count, if not, raise the InvalidArgumentValueError. If enable_cluster_autoscaler (in update mode, this could be update_cluster_autoscaler) is not enabled, it will check whether any of min_count or max_count is assigned, if so, raise the RequiredArgumentMissingError. :return: None
__validate_counts_in_autoscaler
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/agentpool_decorator.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/agentpool_decorator.py
MIT
def get_resource_group_name(self) -> str: """Obtain the value of resource_group_name. Note: resource_group_name will not be decorated into the `agentpool` object. This is a required parameter and its value should be provided by user explicitly. :return: string """ # read the original value passed by the command resource_group_name = self.raw_param.get("resource_group_name") # this parameter does not need dynamic completion # this parameter does not need validation return resource_group_name
Obtain the value of resource_group_name. Note: resource_group_name will not be decorated into the `agentpool` object. This is a required parameter and its value should be provided by user explicitly. :return: string
get_resource_group_name
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acs/agentpool_decorator.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acs/agentpool_decorator.py
MIT