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 _get_token_with_username_and_password(login_server, username, password, repository=None, artifact_repository=None, permission=None, is_login_context=False, is_diagnostics_context=False): """Decides and obtains credentials for a registry using username and password. To be used for scoped access credentials. :param str login_server: The registry login server URL to log in to :param bool only_refresh_token: Whether to ask for only refresh token, or for both refresh and access tokens :param str repository: Repository for which the access token is requested :param str artifact_repository: Artifact repository for which the access token is requested :param str permission: The requested permission on the repository, '*' or 'pull' """ if is_login_context: return username, password token_params = _handle_challenge_phase( login_server, repository, artifact_repository, permission, False, is_diagnostics_context ) from ._errors import ErrorClass if isinstance(token_params, ErrorClass): if is_diagnostics_context: return token_params raise CLIError(token_params.get_error_message()) if ALLOWS_BASIC_AUTH in token_params: return username, password if repository: scope = 'repository:{}:{}'.format(repository, permission) elif artifact_repository: scope = 'artifact-repository:{}:{}'.format(artifact_repository, permission) else: # Registry level permissions only have * as permission, even for a read operation scope = 'registry:{}:*'.format(permission) authurl = urlparse(token_params['realm']) authhost = urlunparse((authurl[0], authurl[1], '/oauth2/token', '', '', '')) headers = {'Content-Type': 'application/x-www-form-urlencoded'} content = { 'service': token_params['service'], 'grant_type': 'password', 'username': username, 'password': password, 'scope': scope } logger.debug(add_timestamp("Sending a HTTP Post request to {}".format(authhost))) response = requests.post(url=authhost, data=urlencode(content), headers=headers, verify=not should_disable_connection_verify()) if response.status_code != 200: from ._errors import CONNECTIVITY_ACCESS_TOKEN_ERROR if is_diagnostics_context: return CONNECTIVITY_ACCESS_TOKEN_ERROR.format_error_message(login_server, response.status_code) raise CLIError(CONNECTIVITY_ACCESS_TOKEN_ERROR.format_error_message(login_server, response.status_code) .get_error_message()) access_token = loads(response.content.decode("utf-8"))["access_token"] return EMPTY_GUID, access_token
Decides and obtains credentials for a registry using username and password. To be used for scoped access credentials. :param str login_server: The registry login server URL to log in to :param bool only_refresh_token: Whether to ask for only refresh token, or for both refresh and access tokens :param str repository: Repository for which the access token is requested :param str artifact_repository: Artifact repository for which the access token is requested :param str permission: The requested permission on the repository, '*' or 'pull'
_get_token_with_username_and_password
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acr/_docker_utils.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acr/_docker_utils.py
MIT
def _get_credentials(cmd, # pylint: disable=too-many-statements registry_name, tenant_suffix, username, password, only_refresh_token, repository=None, artifact_repository=None, permission=None, is_login_context=False, resource_group_name=None): """Try to get AAD authorization tokens or admin user credentials. :param str registry_name: The name of container registry :param str tenant_suffix: The registry login server tenant suffix :param str username: The username used to log into the container registry :param str password: The password used to log into the container registry :param bool only_refresh_token: Whether to ask for only refresh token, or for both refresh and access tokens :param str repository: Repository for which the access token is requested :param str artifact_repository: Artifact repository for which the access token is requested :param str permission: The requested permission on the repository, '*' or 'pull' """ # Raise an error if password is specified but username isn't if not username and password: raise CLIError('Please also specify username if password is specified.') cli_ctx = cmd.cli_ctx resource_not_found, registry = None, None try: registry, resource_group_name = get_registry_by_name(cli_ctx, registry_name, resource_group_name) login_server = registry.login_server if tenant_suffix: logger.warning( "Obtained registry login server '%s' from service. The specified suffix '%s' is ignored.", login_server, tenant_suffix) except (ResourceNotFound, CLIError) as e: resource_not_found = str(e) logger.debug("Could not get registry from service. Exception: %s", resource_not_found) if not isinstance(e, ResourceNotFound) and _AZ_LOGIN_MESSAGE not in resource_not_found: raise # Try to use the pre-defined login server suffix to construct login server from registry name. login_server_suffix = get_login_server_suffix(cli_ctx) if not login_server_suffix: raise login_server = '{}{}{}'.format( registry_name, '-{}'.format(tenant_suffix) if tenant_suffix else '', login_server_suffix).lower() # Validate the login server is reachable url = 'https://' + login_server + '/v2/' try: logger.debug(add_timestamp("Sending a HTTP Get request to {}".format(url))) challenge = requests.get(url, verify=not should_disable_connection_verify()) if challenge.status_code == 403: raise CLIError("Looks like you don't have access to registry '{}'. " "To see configured firewall rules, run 'az acr show --query networkRuleSet --name {}'. " "To see if public network access is enabled, run 'az acr show --query publicNetworkAccess'." "Please refer to https://aka.ms/acr/errors#connectivity_forbidden_error for more information." # pylint: disable=line-too-long .format(login_server, registry_name)) except RequestException as e: logger.debug("Could not connect to registry login server. Exception: %s", str(e)) if resource_not_found: logger.warning("%s\nUsing '%s' as the default registry login server.", resource_not_found, login_server) from .check_health import ACR_CHECK_HEALTH_MSG check_health_msg = ACR_CHECK_HEALTH_MSG.format(registry_name) raise CLIError("Could not connect to the registry login server '{}'. " "Please verify that the registry exists and the URL '{}' is reachable from your environment.\n{}" .format(login_server, url, check_health_msg)) # 1. if username was specified, verify that password was also specified if username: if not password: try: password = prompt_pass(msg='Password: ') except NoTTYException: raise CLIError('Please specify both username and password in non-interactive mode.') username, password = _get_token_with_username_and_password( login_server, username, password, repository, artifact_repository, permission, is_login_context ) return login_server, username, password # 2. if we don't yet have credentials, attempt to get a refresh token if not registry or registry.sku.name in get_managed_sku(cmd): logger.info("Attempting to retrieve AAD refresh token...") try: use_acr_audience = False if registry: aad_auth_policy = acr_config_authentication_as_arm_show(cmd, registry_name, resource_group_name) use_acr_audience = (aad_auth_policy and aad_auth_policy.status == 'disabled') return login_server, EMPTY_GUID, _get_aad_token(cli_ctx, login_server, only_refresh_token, repository, artifact_repository, permission, use_acr_audience=use_acr_audience) except CLIError as e: raise_toomanyrequests_error(str(e)) logger.warning("%s: %s", AAD_TOKEN_BASE_ERROR_MESSAGE, str(e)) # 3. if we still don't have credentials, attempt to get the admin credentials (if enabled) if registry: if registry.admin_user_enabled: logger.info("Attempting with admin credentials...") try: cred = cf_acr_registries(cli_ctx).list_credentials(resource_group_name, registry_name) return login_server, cred.username, cred.passwords[0].value except CLIError as e: logger.warning("%s: %s", ADMIN_USER_BASE_ERROR_MESSAGE, str(e)) else: logger.warning("%s: %s", ADMIN_USER_BASE_ERROR_MESSAGE, "Admin user is disabled.") else: logger.warning("%s: %s", ADMIN_USER_BASE_ERROR_MESSAGE, resource_not_found) # 4. if we still don't have credentials, prompt the user try: username = prompt('Username: ') password = prompt_pass(msg='Password: ') username, password = _get_token_with_username_and_password( login_server, username, password, repository, artifact_repository, permission, is_login_context ) return login_server, username, password except NoTTYException: raise CLIError( 'Unable to authenticate using AAD or admin login credentials. ' + 'Please specify both username and password in non-interactive mode.') return login_server, None, None
Try to get AAD authorization tokens or admin user credentials. :param str registry_name: The name of container registry :param str tenant_suffix: The registry login server tenant suffix :param str username: The username used to log into the container registry :param str password: The password used to log into the container registry :param bool only_refresh_token: Whether to ask for only refresh token, or for both refresh and access tokens :param str repository: Repository for which the access token is requested :param str artifact_repository: Artifact repository for which the access token is requested :param str permission: The requested permission on the repository, '*' or 'pull'
_get_credentials
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acr/_docker_utils.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acr/_docker_utils.py
MIT
def get_login_credentials(cmd, registry_name, tenant_suffix=None, username=None, password=None, resource_group_name=None): """Try to get AAD authorization tokens or admin user credentials to log into a registry. :param str registry_name: The name of container registry :param str username: The username used to log into the container registry :param str password: The password used to log into the container registry """ return _get_credentials(cmd, registry_name, tenant_suffix, username, password, only_refresh_token=True, is_login_context=True, resource_group_name=resource_group_name)
Try to get AAD authorization tokens or admin user credentials to log into a registry. :param str registry_name: The name of container registry :param str username: The username used to log into the container registry :param str password: The password used to log into the container registry
get_login_credentials
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acr/_docker_utils.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acr/_docker_utils.py
MIT
def get_access_credentials(cmd, registry_name, tenant_suffix=None, username=None, password=None, repository=None, artifact_repository=None, permission=None, resource_group_name=None): """Try to get AAD authorization tokens or admin user credentials to access a registry. :param str registry_name: The name of container registry :param str username: The username used to log into the container registry :param str password: The password used to log into the container registry :param str repository: Repository for which the access token is requested :param str artifact_repository: Artifact repository for which the access token is requested :param str permission: The requested permission on the repository """ return _get_credentials(cmd, registry_name, tenant_suffix, username, password, only_refresh_token=False, repository=repository, artifact_repository=artifact_repository, permission=permission, resource_group_name=resource_group_name)
Try to get AAD authorization tokens or admin user credentials to access a registry. :param str registry_name: The name of container registry :param str username: The username used to log into the container registry :param str password: The password used to log into the container registry :param str repository: Repository for which the access token is requested :param str artifact_repository: Artifact repository for which the access token is requested :param str permission: The requested permission on the repository
get_access_credentials
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acr/_docker_utils.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acr/_docker_utils.py
MIT
def log_registry_response(response): """Log the HTTP request and response of a registry API call. :param Response response: The response object """ log_request(None, response.request) log_response(None, response.request, RegistryResponse(response.request, response))
Log the HTTP request and response of a registry API call. :param Response response: The response object
log_registry_response
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acr/_docker_utils.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acr/_docker_utils.py
MIT
def get_login_server_suffix(cli_ctx): """Get the Azure Container Registry login server suffix in the current cloud.""" try: return cli_ctx.cloud.suffixes.acr_login_server_endpoint except CloudSuffixNotSetException as e: logger.debug("Could not get login server endpoint suffix. Exception: %s", str(e)) # Ignore the error if the suffix is not set, the caller should then try to get login server from server. return None
Get the Azure Container Registry login server suffix in the current cloud.
get_login_server_suffix
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acr/_docker_utils.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acr/_docker_utils.py
MIT
def get_authorization_header(username, password): """Get the authorization header as Basic auth if username is provided, or Bearer auth otherwise :param str username: The username used to log into the container registry :param str password: The password used to log into the container registry """ if username == EMPTY_GUID: auth = _get_bearer_auth_str(password) else: auth = _get_basic_auth_str(username, password) return {'Authorization': auth}
Get the authorization header as Basic auth if username is provided, or Bearer auth otherwise :param str username: The username used to log into the container registry :param str password: The password used to log into the container registry
get_authorization_header
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acr/_docker_utils.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acr/_docker_utils.py
MIT
def acr_update_get(cmd): """Returns an empty RegistryUpdateParameters object. """ RegistryUpdateParameters = cmd.get_models('RegistryUpdateParameters') return RegistryUpdateParameters()
Returns an empty RegistryUpdateParameters object.
acr_update_get
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acr/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acr/custom.py
MIT
def acr_cred_set_update_get(cmd): """Returns an empty CredentialSetUpdateParameters object. """ CredSetUpdateParameters = cmd.get_models('CredentialSetUpdateParameters', operation_group='credential_sets') return CredSetUpdateParameters()
Returns an empty CredentialSetUpdateParameters object.
acr_cred_set_update_get
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acr/credential_set.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acr/credential_set.py
MIT
def acr_webhook_update_get(cmd): """Returns an empty WebhookUpdateParameters object. """ WebhookUpdateParameters = cmd.get_models('WebhookUpdateParameters') return WebhookUpdateParameters()
Returns an empty WebhookUpdateParameters object.
acr_webhook_update_get
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acr/webhook.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acr/webhook.py
MIT
def acr_replication_update_get(cmd): """Returns an empty ReplicationUpdateParameters object. """ ReplicationUpdateParameters = cmd.get_models('ReplicationUpdateParameters') return ReplicationUpdateParameters()
Returns an empty ReplicationUpdateParameters object.
acr_replication_update_get
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acr/replication.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acr/replication.py
MIT
def get_acr_service_client(cli_ctx, api_version=None): """Returns the client for managing container registries. """ from azure.cli.core.profiles import ResourceType return get_mgmt_service_client(cli_ctx, ResourceType.MGMT_CONTAINERREGISTRY, api_version=api_version)
Returns the client for managing container registries.
get_acr_service_client
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acr/_client_factory.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acr/_client_factory.py
MIT
def _get_triggers(item): """Get a nested value from a dict. :param dict item: The dict object """ triggers = [] if _get_value(item, 'trigger', 'sourceTriggers', 0, 'status').lower() == 'enabled': triggers.append('SOURCE') if _get_trigger_status(item, 'trigger', 'timerTriggers'): triggers.append('TIMER') if _get_value(item, 'trigger', 'baseImageTrigger', 'status').lower() == 'enabled': triggers.append('BASE_IMAGE') triggers.sort() return ' ' if not triggers else str(', '.join(triggers))
Get a nested value from a dict. :param dict item: The dict object
_get_triggers
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acr/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acr/_format.py
MIT
def _get_value(item, *args): """Get a nested value from a dict. :param dict item: The dict object """ try: for arg in args: item = item[arg] return str(item) if item or item == 0 else ' ' except (KeyError, TypeError, IndexError): return ' '
Get a nested value from a dict. :param dict item: The dict object
_get_value
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acr/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acr/_format.py
MIT
def _get_array_value(item, *args): """Get a nested array value from a dict. :param dict item: The dict object """ try: for arg in args: item = item[arg] return list(item) if item else [] except (KeyError, TypeError, IndexError): return []
Get a nested array value from a dict. :param dict item: The dict object
_get_array_value
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acr/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acr/_format.py
MIT
def _get_trigger_status(item, *args): """Check if at least one enabled trigger exists in a list. :param dict item: The dict object """ try: for arg in args: item = item[arg] enabled = False if item: for trigger in item: if trigger['status'].lower() == "enabled": enabled = True break return enabled except (KeyError, TypeError, IndexError): return False
Check if at least one enabled trigger exists in a list. :param dict item: The dict object
_get_trigger_status
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acr/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acr/_format.py
MIT
def acr_helm_install_cli(client_version='2.16.3', install_location=None, yes=False): """Install Helm command-line tool.""" if client_version >= '3': logger.warning('Please note that "az acr helm" commands do not work with Helm 3, ' 'but you can still push Helm chart to ACR using a different command flow. ' 'For more information, please check out ' 'https://learn.microsoft.com/azure/container-registry/container-registry-helm-repos') install_location, install_dir, cli = _process_helm_install_location_info(install_location) client_version = "v%s" % client_version source_url = 'https://get.helm.sh/{}' package, folder = _get_helm_package_name(client_version) download_path = '' if not package: raise CLIError('No prebuilt binary for current system.') try: import tempfile with tempfile.TemporaryDirectory() as tmp_dir: download_path = os.path.join(tmp_dir, package) _urlretrieve(source_url.format(package), download_path) _unzip(download_path, tmp_dir) sub_dir = os.path.join(tmp_dir, folder) # Ask user to check license if not yes: with open(os.path.join(sub_dir, 'LICENSE')) as f: text = f.read() logger.warning(text) user_confirmation('Before proceeding with the installation, ' 'please confirm that you have read and agreed the above license.') # Move files from temporary location to specified location import shutil import stat for f in os.scandir(sub_dir): # Rename helm to specified name target_path = install_location if os.path.splitext(f.name)[0] == 'helm' \ else os.path.join(install_dir, f.name) logger.debug('Moving %s to %s', f.path, target_path) shutil.move(f.path, target_path) if os.path.splitext(f.name)[0] in ('helm', 'tiller'): os.chmod(target_path, os.stat(target_path).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) except OSError as e: import traceback logger.debug(traceback.format_exc()) raise CLIError('Error while installing {} to {}: {}'.format(cli, install_dir, e)) logger.warning('Successfully installed %s to %s.', cli, install_dir) # Remind user to add to path system = platform.system() if system == 'Windows': # be verbose, as the install_location likely not in Windows's search PATHs env_paths = os.environ['PATH'].split(';') found = next((x for x in env_paths if x.lower().rstrip('\\') == install_dir.lower()), None) if not found: # pylint: disable=logging-format-interpolation logger.warning('Please add "{0}" to your search PATH so the `{1}` can be found. 2 options: \n' ' 1. Run "set PATH=%PATH%;{0}" or "$env:path += \'{0}\'" for PowerShell. ' 'This is good for the current command session.\n' ' 2. Update system PATH environment variable by following ' '"Control Panel->System->Advanced->Environment Variables", and re-open the command window. ' 'You only need to do it once'.format(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 Helm command-line tool.
acr_helm_install_cli
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acr/helm.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acr/helm.py
MIT
def test_acr_image_import(self, resource_group): '''There are nine test cases. Case 1: Import image from a registry in a different subscription from the current one Case 2: Import image from one registry to another where both registries belong to the same subscription Case 3: Import image to the target registry and keep the repository:tag the same as that in the source Case 4: Import image to enable multiple tags in the target registry Case 5: Import image within the same registry Case 6: Import image by manifest digest Case 7: Import image from a registry in Docker Hub Case 8: Import image from an Azure Container Registry with Service Principal's credentials Case 9: Import image from an Azure Container Registry with personal access token ''' source_registry_name = self.create_random_name("sourceregistrysamesub", 40) registry_name = self.create_random_name("targetregistry", 20) token = self.cmd('account get-access-token').get_output_in_json()['accessToken'] # service principal creds to support import from resource_imageV1 #service_principal_username = self.cmd('keyvault secret show --id https://cliimportkv73021.vault.azure.net/secrets/SPusername').get_output_in_json()['value'] #service_principal_password = self.cmd('keyvault secret show --id https://cliimportkv73021.vault.azure.net/secrets/SPpassword').get_output_in_json()['value'] self.kwargs.update({ 'resource_id': '/subscriptions/dfb63c8c-7c89-4ef8-af13-75c1d873c895/resourcegroups/resourcegroupdiffsub/providers/Microsoft.ContainerRegistry/registries/sourceregistrydiffsub', 'resource_imageV1': 'sourceregistrydiffsub.azurecr.io/microsoft:azure-cli-1', 'resource_imageV2': 'sourceregistrydiffsub.azurecr.io/microsoft:azure-cli-2', 'source_registry_rg': 'resourcegroupsamesub', 'source_loc': 'westus', 'source_registry_name': source_registry_name, 'registry_name': registry_name, 'sku': 'Standard', 'rg_loc': 'eastus', 'source_image': 'microsoft:azure-cli', 'source_image_same_registry': '{}.azurecr.io/microsoft:azure-cli'.format(registry_name), 'source_image_by_digest': '{}.azurecr.io/azure-cli@sha256:622731d3e3a16b11a1f318b1c5018d0c44996b4c096b864fe2eac5b8beab535a'.format(source_registry_name), 'tag_same_sub': 'repository_same_sub:tag_same_sub', 'tag_multitag1': 'repository_multi1:tag_multi1', 'tag_multitag2': 'repository_multi2:tag_multi2', 'tag_same_registry': 'repository_same_registry:tag_same_registry', 'tag_by_digest': 'repository_by_digest:tag_by_digest', 'source_image_public_registry_dockerhub': 'registry.hub.docker.com/library/hello-world', # 'application_ID': service_principal_username, #'service_principal_password': service_principal_password, 'token': token }) # create a resource group for the source registry self.cmd('group create -n {source_registry_rg} -l {source_loc}') # create a source registry which stays in the same subscription as the target registry does self.cmd('acr create -n {source_registry_name} -g {source_registry_rg} -l {source_loc} --sku {sku}', checks=[self.check('name', '{source_registry_name}'), self.check('location', '{source_loc}'), self.check('adminUserEnabled', False), self.check('sku.name', 'Standard'), self.check('sku.tier', 'Standard'), self.check('provisioningState', 'Succeeded')]) # Case 1: Import image from a registry in a different subscription from the current one self.cmd('acr import -n {source_registry_name} -r {resource_id} --source {source_image}') # create a target registry to hold the imported images self.cmd('acr create -n {registry_name} -g {rg} -l {rg_loc} --sku {sku}', checks=[self.check('name', '{registry_name}'), self.check('location', '{rg_loc}'), self.check('adminUserEnabled', False), self.check('sku.name', 'Standard'), self.check('sku.tier', 'Standard'), self.check('provisioningState', 'Succeeded')]) # Case 2: Import image from one registry to another where both registries belong to the same subscription self.cmd('acr import -n {registry_name} --source {source_image} -r {source_registry_name} -t {tag_same_sub}') # Case 3: Import image to the target registry and keep the repository:tag the same as that in the source self.cmd('acr import -n {registry_name} --source {source_image} -r {source_registry_name}') # Case 4: Import image to enable multiple tags in the target registry self.cmd('acr import -n {registry_name} --source {source_image} -r {source_registry_name} -t {tag_multitag1} -t {tag_multitag2}') # Case 5: Import image within the same registry self.cmd('acr import -n {registry_name} --source {source_image_same_registry} -t {tag_same_registry}') # Case 6: Import image by manifest digest self.cmd('acr import -n {registry_name} --source {source_image_by_digest} -t {tag_by_digest}') # Case 7: Import image from a public registry in dockerhub self.cmd('acr import -n {registry_name} --source {source_image_public_registry_dockerhub}') # Case 8: Import image from an Azure Container Registry with Service Principal's credentials #self.cmd('acr import -n {registry_name} --source {resource_imageV1} -u {application_ID} -p {service_principal_password}') # Case 9: Import image from an Azure Container Registry with personal access token self.cmd('acr import -n {registry_name} --source {resource_imageV2} -p {token}')
There are nine test cases. Case 1: Import image from a registry in a different subscription from the current one Case 2: Import image from one registry to another where both registries belong to the same subscription Case 3: Import image to the target registry and keep the repository:tag the same as that in the source Case 4: Import image to enable multiple tags in the target registry Case 5: Import image within the same registry Case 6: Import image by manifest digest Case 7: Import image from a registry in Docker Hub Case 8: Import image from an Azure Container Registry with Service Principal's credentials Case 9: Import image from an Azure Container Registry with personal access token
test_acr_image_import
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/acr/tests/latest/test_acr_commands.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/acr/tests/latest/test_acr_commands.py
MIT
def cli_billing_list_invoices(client, generate_url=False): """List all available invoices of the subscription""" return client.list(expand='downloadUrl' if generate_url else None)
List all available invoices of the subscription
cli_billing_list_invoices
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/billing/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/billing/custom.py
MIT
def cli_billing_get_invoice(client, name=None): """Retrieve invoice of specific name of the subscription""" if name: return client.get(name) return client.get_latest()
Retrieve invoice of specific name of the subscription
cli_billing_get_invoice
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/billing/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/billing/custom.py
MIT
def billing_invoice_download(client, account_name=None, invoice_name=None, download_token=None, download_urls=None): """ Get URL to download invoice :param account_name: The ID that uniquely identifies a billing account. :param invoice_name: The ID that uniquely identifies an invoice. :param download_token: The download token with document source and document ID. :param download_urls: An array of download urls for individual. """ if account_name and invoice_name and download_token: return client.begin_download_invoice(account_name, invoice_name, download_token) if account_name and download_urls: return client.begin_download_multiple_billing_profile_invoices(account_name, download_urls) if download_urls: return client.begin_download_multiple_billing_subscription_invoices(download_urls) if invoice_name and download_token: return client.begin_download_billing_subscription_invoice( invoice_name, download_token ) from azure.cli.core.azclierror import CLIInternalError raise CLIInternalError( "Uncaught argument combinations for Azure CLI to handle. Please submit an issue" )
Get URL to download invoice :param account_name: The ID that uniquely identifies a billing account. :param invoice_name: The ID that uniquely identifies an invoice. :param download_token: The download token with document source and document ID. :param download_urls: An array of download urls for individual.
billing_invoice_download
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/billing/manual/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/billing/manual/custom.py
MIT
def _get_resource_group_from_account_name(client, account_name): """ Fetch resource group from vault name :param str vault_name: name of the key vault :return: resource group name or None :rtype: str """ from azure.mgmt.core.tools import parse_resource_id for acct in client.list(): id_comps = parse_resource_id(acct.id) if id_comps['name'] == account_name: return id_comps['resource_group'] raise CLIError( "The Resource 'Microsoft.DataLakeStore/accounts/{}'".format(account_name) + " not found within subscription: {}".format(client.config.subscription_id))
Fetch resource group from vault name :param str vault_name: name of the key vault :return: resource group name or None :rtype: str
_get_resource_group_from_account_name
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/dls/_validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/dls/_validators.py
MIT
def apim_list(client, resource_group_name=None): """List all APIM instances. Resource group is optional """ if resource_group_name: return client.api_management_service.list_by_resource_group(resource_group_name) return client.api_management_service.list()
List all APIM instances. Resource group is optional
apim_list
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_get(client, resource_group_name, name): """Show details of an APIM instance """ return client.api_management_service.get(resource_group_name, name)
Show details of an APIM instance
apim_get
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_check_name_availability(client, name): """checks to see if a service name is available to use """ parameters = ApiManagementServiceCheckNameAvailabilityParameters( name=name) return client.api_management_service.check_name_availability(parameters)
checks to see if a service name is available to use
apim_check_name_availability
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_backup(client, resource_group_name, name, backup_name, storage_account_name, storage_account_container, storage_account_key): """back up an API Management service to the configured storage account """ parameters = ApiManagementServiceBackupRestoreParameters( storage_account=storage_account_name, access_key=storage_account_key, container_name=storage_account_container, backup_name=backup_name) return client.api_management_service.begin_backup(resource_group_name, name, parameters)
back up an API Management service to the configured storage account
apim_backup
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_restore(client, resource_group_name, name, backup_name, storage_account_name, storage_account_container, storage_account_key): """Restore an API Management service to the configured storage account """ parameters = ApiManagementServiceBackupRestoreParameters( storage_account=storage_account_name, access_key=storage_account_key, container_name=storage_account_container, backup_name=backup_name) return client.api_management_service.begin_restore(resource_group_name, name, parameters)
Restore an API Management service to the configured storage account
apim_restore
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_apply_network_configuration_updates(client, resource_group_name, name, location=None): """Update the API Management resource running in the virtual network to pick the updated network settings. """ properties = {} if location is not None: properties['location'] = location return client.api_management_service.begin_apply_network_configuration_updates(resource_group_name, name, properties)
Update the API Management resource running in the virtual network to pick the updated network settings.
apim_apply_network_configuration_updates
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_schema_create(client, resource_group_name, service_name, api_id, schema_id, schema_type, schema_name=None, schema_path=None, schema_content=None, resource_type=None, no_wait=False): """creates or updates an API Schema. """ if schema_path is not None and schema_content is None: api_file = open(schema_path, 'r') content_value = api_file.read() value = content_value elif schema_content is not None and schema_path is None: value = schema_content elif schema_path is not None and schema_content is not None: raise MutuallyExclusiveArgumentError( "Can't specify schema_path and schema_content at the same time.") else: raise RequiredArgumentMissingError( "Please either specify schema_path or schema_content.") parameters = SchemaContract( id=schema_id, name=schema_name, type=resource_type, content_type=schema_type, value=value ) return sdk_no_wait(no_wait, client.api_schema.begin_create_or_update, resource_group_name=resource_group_name, service_name=service_name, api_id=api_id, schema_id=schema_id, parameters=parameters)
creates or updates an API Schema.
apim_api_schema_create
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_schema_delete(client, resource_group_name, service_name, api_id, schema_id, if_match=None, no_wait=False): """Deletes an API Schema. """ return sdk_no_wait(no_wait, client.api_schema.delete, resource_group_name=resource_group_name, service_name=service_name, api_id=api_id, schema_id=schema_id, if_match="*" if if_match is None else if_match)
Deletes an API Schema.
apim_api_schema_delete
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_schema_get(client, resource_group_name, service_name, api_id, schema_id): """Shows details of an API Schema. """ return client.api_schema.get(resource_group_name=resource_group_name, service_name=service_name, api_id=api_id, schema_id=schema_id)
Shows details of an API Schema.
apim_api_schema_get
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_schema_entity(client, resource_group_name, service_name, api_id, schema_id): """Shows details of an API Schema. """ return client.api_schema.get_entity_tag(resource_group_name=resource_group_name, service_name=service_name, api_id=api_id, schema_id=schema_id)
Shows details of an API Schema.
apim_api_schema_entity
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_schema_list(client, resource_group_name, api_id, service_name, filter_display_name=None, top=None, skip=None): """Get the schema configuration at the API level. """ return client.api_schema.list_by_api(resource_group_name, service_name, api_id, filter=filter_display_name, skip=skip, top=top)
Get the schema configuration at the API level.
apim_api_schema_list
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_create(client, resource_group_name, service_name, api_id, description=None, subscription_key_header_name=None, subscription_key_query_param_name=None, open_id_provider_id=None, bearer_token_sending_methods=None, authorization_server_id=None, authorization_scope=None, display_name=None, service_url=None, protocols=None, path=None, subscription_key_required=None, api_type=None, subscription_required=False, no_wait=False): """Creates a new API. """ if authorization_server_id is not None: o_auth2 = OAuth2AuthenticationSettingsContract( authorization_server_id=authorization_server_id, scope=authorization_scope ) authentication_settings = AuthenticationSettingsContract( o_auth2=o_auth2, subscription_key_required=subscription_key_required ) elif open_id_provider_id is not None and bearer_token_sending_methods is not None: openid = OpenIdAuthenticationSettingsContract( openid_provider_id=open_id_provider_id, bearer_token_sending_methods=bearer_token_sending_methods ) authentication_settings = AuthenticationSettingsContract( openid=openid, subscription_key_required=subscription_key_required ) else: authentication_settings = None parsed_url = urlparse(service_url) if protocols is None: if parsed_url.scheme in (Protocol.WS.value, Protocol.WSS.value): protocols = [Protocol.WSS.value] else: protocols = [Protocol.HTTPS.value] if api_type is None: if parsed_url.scheme in (Protocol.WS.value, Protocol.WSS.value): api_type = ApiType.WEBSOCKET.value else: api_type = ApiType.HTTP.value parameters = ApiContract( api_id=api_id, description=description, authentication_settings=authentication_settings, subscription_key_parameter_names=_get_subscription_key_parameter_names( subscription_key_query_param_name, subscription_key_header_name), display_name=display_name, service_url=service_url, protocols=protocols, path=path, api_type=api_type, subscription_required=subscription_required ) return sdk_no_wait(no_wait, client.api.begin_create_or_update, resource_group_name=resource_group_name, service_name=service_name, api_id=api_id, parameters=parameters)
Creates a new API.
apim_api_create
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_get(client, resource_group_name, service_name, api_id): """Shows details of an API. """ return client.api.get(resource_group_name=resource_group_name, service_name=service_name, api_id=api_id)
Shows details of an API.
apim_api_get
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_list(client, resource_group_name, service_name, filter_display_name=None, top=None, skip=None): """List all APIs of an API Management instance. """ if filter_display_name is not None: filter_display_name = "properties/displayName eq '%s'" % filter_display_name return client.api.list_by_service(resource_group_name, service_name, filter=filter_display_name, skip=skip, top=top)
List all APIs of an API Management instance.
apim_api_list
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_delete( client, resource_group_name, service_name, api_id, delete_revisions=None, if_match=None, no_wait=False): """Deletes an existing API. """ cms = client.api return sdk_no_wait( no_wait, cms.delete, resource_group_name=resource_group_name, service_name=service_name, api_id=api_id, if_match="*" if if_match is None else if_match, delete_revisions=delete_revisions if delete_revisions is not None else False)
Deletes an existing API.
apim_api_delete
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_update(instance, description=None, subscription_key_header_name=None, subscription_key_query_param_name=None, display_name=None, service_url=None, protocols=None, path=None, api_type=None, subscription_required=None, tags=None): """Updates an existing API. """ if description is not None: instance.description = description if subscription_key_header_name is not None: instance.subscription_key_parameter_names = _get_subscription_key_parameter_names( subscription_key_query_param_name, subscription_key_header_name) if display_name is not None: instance.display_name = display_name if service_url is not None: instance.service_url = service_url if protocols is not None: instance.protocols = protocols if path is not None: instance.path = path if api_type is not None: instance.api_type = api_type if subscription_required is not None: instance.subscription_required = subscription_required if tags is not None: instance.tags = tags return instance
Updates an existing API.
apim_api_update
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_import( client, resource_group_name, service_name, path, specification_format, description=None, subscription_key_header_name=None, subscription_key_query_param_name=None, api_id=None, api_revision=None, api_version=None, api_version_set_id=None, display_name=None, service_url=None, protocols=None, specification_path=None, specification_url=None, api_type=None, subscription_required=None, soap_api_type=None, wsdl_endpoint_name=None, wsdl_service_name=None, no_wait=False): """Import a new API""" cms = client.api # api_type: Type of API. Possible values include: 'http', 'soap' # possible parameter format is 'wadl-xml', 'wadl-link-json', 'swagger-json', 'swagger-link-json', # 'wsdl', 'wsdl-link', 'openapi', 'openapi+json', 'openapi-link' # possible parameter specificationFormat is 'Wadl', 'Swagger', 'OpenApi', 'OpenApiJson', 'Wsdl' parameters = ApiCreateOrUpdateParameter( path=path, protocols=protocols, service_url=service_url, display_name=display_name, description=description, subscription_required=subscription_required, subscription_key_parameter_names=_get_subscription_key_parameter_names( subscription_key_query_param_name, subscription_key_header_name), api_version=api_version, api_version_set_id=_get_vs_fullpath(api_version_set_id) ) if api_revision is not None and api_id is not None: api_id = api_id + ";rev=" + api_revision if api_revision is not None and api_id is None: api_id = uuid.uuid4().hex + ";rev=" + api_revision elif api_id is None: api_id = uuid.uuid4().hex if specification_path is not None and specification_url is None: api_file = open(specification_path, 'r') content_value = api_file.read() parameters.value = content_value elif specification_url is not None and specification_path is None: parameters.value = specification_url elif specification_path is not None and specification_url is not None: raise MutuallyExclusiveArgumentError( "Can't specify specification-url and specification-path at the same time.") else: raise RequiredArgumentMissingError( "Please either specify specification-url or specification-path.") FORMAT_MAPPINGS = { ImportFormat.Wadl.value: { # specification_path is not none True: ContentFormat.WADL_XML.value, # specification_url is not none False: ContentFormat.WADL_LINK_JSON.value }, ImportFormat.Swagger.value: { True: ContentFormat.SWAGGER_JSON.value, False: ContentFormat.SWAGGER_LINK_JSON.value }, ImportFormat.OpenApi.value: { True: ContentFormat.OPENAPI.value, False: ContentFormat.OPENAPI_LINK.value }, ImportFormat.OpenApiJson.value: { True: ContentFormat.OPENAPI_JSON.value, False: ContentFormat.OPENAPI_JSON_LINK.value }, ImportFormat.Wsdl.value: { True: ContentFormat.WSDL.value, False: ContentFormat.WSDL_LINK.value }, ImportFormat.GraphQL.value: { True: ContentFormat.GRAPHQL_LINK.value, False: ContentFormat.GRAPHQL_LINK.value } } if specification_format in FORMAT_MAPPINGS: parameters.format = FORMAT_MAPPINGS[specification_format][specification_path is not None] else: raise InvalidArgumentValueError( "SpecificationFormat: " + specification_format + "is not supported.") if specification_format == ImportFormat.Wsdl.value: if api_type == ApiType.http.value: soap_api_type = SoapApiType.soap_to_rest.value else: soap_api_type = SoapApiType.soap_pass_through.value parameters.soap_api_type = soap_api_type if wsdl_service_name is not None and wsdl_endpoint_name is not None: parameters.wsdl_selector = ApiCreateOrUpdatePropertiesWsdlSelector( wsdl_service_name=wsdl_service_name, wsdl_endpoint_name=wsdl_endpoint_name ) return sdk_no_wait( no_wait, cms.begin_create_or_update, resource_group_name=resource_group_name, service_name=service_name, api_id=api_id, parameters=parameters)
Import a new API
apim_api_import
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_export(client, resource_group_name, service_name, api_id, export_format, file_path=None): """Gets the details of the API specified by its identifier in the format specified """ import json import yaml import xml.etree.ElementTree as ET import os import requests # Define the mapping from old format values to new ones format_mapping = { "WadlFile": "wadl-link", "SwaggerFile": "swagger-link", "OpenApiYamlFile": "openapi-link", "OpenApiJsonFile": "openapi+json-link", "WsdlFile": "wsdl-link", "WadlUrl": "wadl-link", "SwaggerUrl": "swagger-link", "OpenApiYamlUrl": "openapi-link", "OpenApiJsonUrl": "openapi+json-link", "WsdlUrl": "wsdl-link" } mappedFormat = format_mapping.get(export_format) # Export the API from APIManagement response = client.api_export.get(resource_group_name, service_name, api_id, mappedFormat, True) # If url is requested if export_format in ['WadlUrl', 'SwaggerUrl', 'OpenApiYamlUrl', 'OpenApiJsonUrl', 'WsdlUrl']: return response # If file is requested if file_path is None: raise RequiredArgumentMissingError( "Please specify file path using '--file-path' argument.") # Obtain link from the response response_dict = api_export_result_to_dict(response) try: # Extract the link from the response where results are stored link = response_dict['additional_properties']['properties']['value']['link'] except KeyError: logger.warning("Error exporting api from APIManagement. The expected link is not present in the response.") # Determine the file extension based on the mappedFormat if mappedFormat in ['swagger-link', 'openapi+json-link']: file_extension = '.json' elif mappedFormat in ['wsdl-link', 'wadl-link']: file_extension = '.xml' elif mappedFormat in ['openapi-link']: file_extension = '.yaml' else: file_extension = '.txt' # Remove '-link' from the mappedFormat and create the file name with full path exportType = mappedFormat.replace('-link', '') file_name = f"{api_id}_{exportType}{file_extension}" full_path = os.path.join(file_path, file_name) # Get the results from the link where the API Export Results are stored try: exportedResults = requests.get(link, timeout=30) if not exportedResults.ok: logger.warning("Got bad status from APIManagement during API Export:%s, {exportedResults.status_code}") except requests.exceptions.ReadTimeout: logger.warning("Timed out while exporting api from APIManagement.") try: # Try to parse as JSON exportedResultContent = json.loads(exportedResults.text) except json.JSONDecodeError: try: # Try to parse as YAML exportedResultContent = yaml.safe_load(exportedResults.text) except yaml.YAMLError: try: # Try to parse as XML exportedResultContent = ET.fromstring(exportedResults.text) except ET.ParseError: logger.warning("Content is not in JSON, YAML, or XML format.") # Write results to a file logger.warning("Writing results to file: %s", full_path) try: with open(full_path, 'w') as f: if file_extension == '.json': json.dump(exportedResultContent, f, indent=4) elif file_extension == '.yaml': yaml.dump(exportedResultContent, f) elif file_extension == '.xml': ET.register_namespace('', 'http://wadl.dev.java.net/2009/02') xml_string = ET.tostring(exportedResultContent, encoding='unicode') f.write(xml_string) else: f.write(str(exportedResultContent)) except OSError as e: logger.warning("Error writing exported API to file.: %s", e) # Write the response to a file return logger.warning("APIMExport results written to file: %s", full_path)
Gets the details of the API specified by its identifier in the format specified
apim_api_export
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_nv_create( client, resource_group_name, service_name, named_value_id, display_name, value=None, tags=None, secret=False, if_match=None, no_wait=False): """Creates a new Named Value. """ parameters = NamedValueCreateContract( tags=tags, secret=secret, display_name=display_name, value=value ) return sdk_no_wait(no_wait, client.named_value.begin_create_or_update, resource_group_name=resource_group_name, service_name=service_name, named_value_id=named_value_id, parameters=parameters, if_match="*" if if_match is None else if_match)
Creates a new Named Value.
apim_nv_create
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_nv_get(client, resource_group_name, service_name, named_value_id): """Shows details of a Named Value. """ return client.named_value.get(resource_group_name, service_name, named_value_id)
Shows details of a Named Value.
apim_nv_get
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_nv_show_secret(client, resource_group_name, service_name, named_value_id): """Gets the secret of the NamedValue.""" return client.named_value.list_value(resource_group_name, service_name, named_value_id)
Gets the secret of the NamedValue.
apim_nv_show_secret
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_nv_list(client, resource_group_name, service_name): """List all Named Values of an API Management instance. """ return client.named_value.list_by_service(resource_group_name, service_name)
List all Named Values of an API Management instance.
apim_nv_list
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_nv_delete(client, resource_group_name, service_name, named_value_id): """Deletes an existing Named Value. """ return client.named_value.delete(resource_group_name, service_name, named_value_id, if_match='*')
Deletes an existing Named Value.
apim_nv_delete
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_nv_update(instance, value=None, tags=None, secret=None): """Updates an existing Named Value.""" if tags is not None: instance.tags = tags if value is not None: instance.value = value if secret is not None: instance.secret = secret return instance
Updates an existing Named Value.
apim_nv_update
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_operation_list(client, resource_group_name, service_name, api_id): """List a collection of the operations for the specified API.""" return client.api_operation.list_by_api(resource_group_name, service_name, api_id)
List a collection of the operations for the specified API.
apim_api_operation_list
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_operation_get(client, resource_group_name, service_name, api_id, operation_id): """Gets the details of the API Operation specified by its identifier.""" return client.api_operation.get(resource_group_name, service_name, api_id, operation_id)
Gets the details of the API Operation specified by its identifier.
apim_api_operation_get
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_operation_create( client, resource_group_name, service_name, api_id, url_template, method, display_name, template_parameters=None, operation_id=None, description=None, if_match=None, no_wait=False): """Creates a new operation in the API or updates an existing one.""" if operation_id is None: operation_id = uuid.uuid4().hex resource = OperationContract( description=description, display_name=display_name, method=method, url_template=url_template, template_parameters=template_parameters) return sdk_no_wait( no_wait, client.api_operation.create_or_update, resource_group_name=resource_group_name, service_name=service_name, api_id=api_id, operation_id=operation_id, parameters=resource, if_match="*" if if_match is None else if_match)
Creates a new operation in the API or updates an existing one.
apim_api_operation_create
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_operation_update(instance, display_name=None, description=None, method=None, url_template=None): """Updates the details of the operation in the API specified by its identifier.""" if display_name is not None: instance.display_name = display_name if description is not None: instance.description = description if method is not None: instance.method = method if url_template is not None: instance.url_template = url_template return instance
Updates the details of the operation in the API specified by its identifier.
apim_api_operation_update
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_operation_delete( client, resource_group_name, service_name, api_id, operation_id, if_match=None, no_wait=False): """Deletes the specified operation in the API.""" return sdk_no_wait( no_wait, client.api_operation.delete, resource_group_name=resource_group_name, service_name=service_name, api_id=api_id, operation_id=operation_id, if_match="*" if if_match is None else if_match)
Deletes the specified operation in the API.
apim_api_operation_delete
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_release_list(client, resource_group_name, service_name, api_id): """Lists all releases of an API.""" return client.api_release.list_by_service(resource_group_name, service_name, api_id)
Lists all releases of an API.
apim_api_release_list
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_release_show(client, resource_group_name, service_name, api_id, release_id): """Returns the details of an API release.""" return client.api_release.get(resource_group_name, service_name, api_id, release_id)
Returns the details of an API release.
apim_api_release_show
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_release_create( client, resource_group_name, service_name, api_id, api_revision, release_id=None, if_match=None, notes=None): """Creates a new Release for the API.""" if release_id is None: release_id = uuid.uuid4().hex api_id_extended_with_revision = "/apis/" + api_id + ";rev=" + api_revision parameter = ApiReleaseContract( notes=notes, api_id=api_id_extended_with_revision) return client.api_release.create_or_update( resource_group_name, service_name, api_id, release_id, parameter, "*" if if_match is None else if_match)
Creates a new Release for the API.
apim_api_release_create
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_release_update(instance, notes=None): """Updates the details of the release of the API specified by its identifier.""" instance.notes = notes return instance
Updates the details of the release of the API specified by its identifier.
apim_api_release_update
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_release_delete(client, resource_group_name, service_name, api_id, release_id, if_match=None): """Deletes the specified release in the API.""" return client.api_release.delete( resource_group_name, service_name, api_id, release_id, "*" if if_match is None else if_match)
Deletes the specified release in the API.
apim_api_release_delete
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_revision_list(client, resource_group_name, service_name, api_id): """Lists all revisions of an API.""" return client.api_revision.list_by_service(resource_group_name, service_name, api_id)
Lists all revisions of an API.
apim_api_revision_list
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_revision_create(client, resource_group_name, service_name, api_id, api_revision, api_revision_description=None, no_wait=False): """Creates a new API Revision. """ cur_api = client.api.get(resource_group_name, service_name, api_id) parameters = ApiCreateOrUpdateParameter( path=cur_api.path, display_name=cur_api.display_name, service_url=cur_api.service_url, authentication_settings=cur_api.authentication_settings, protocols=cur_api.protocols, subscription_key_parameter_names=cur_api.subscription_key_parameter_names, api_revision_description=api_revision_description, source_api_id="/apis/" + api_id ) return sdk_no_wait(no_wait, client.api.begin_create_or_update, resource_group_name=resource_group_name, service_name=service_name, api_id=api_id + ";rev=" + api_revision, parameters=parameters)
Creates a new API Revision.
apim_api_revision_create
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_vs_list(client, resource_group_name, service_name): """Lists a collection of API Version Sets in the specified service instance.""" return client.api_version_set.list_by_service(resource_group_name, service_name)
Lists a collection of API Version Sets in the specified service instance.
apim_api_vs_list
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_vs_show(client, resource_group_name, service_name, version_set_id): """Gets the details of the Api Version Set specified by its identifier.""" return client.api_version_set.get(resource_group_name, service_name, version_set_id)
Gets the details of the Api Version Set specified by its identifier.
apim_api_vs_show
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_vs_create( client, resource_group_name, service_name, display_name, versioning_scheme, version_set_id=None, if_match=None, description=None, version_query_name=None, version_header_name=None, no_wait=False): """Creates or Updates a Api Version Set.""" if version_set_id is None: version_set_id = uuid.uuid4().hex resource = ApiVersionSetContract( description=description, versioning_scheme=versioning_scheme, display_name=display_name) if versioning_scheme == VersioningScheme.header: if version_header_name is None: raise RequiredArgumentMissingError( "Please specify version header name while using 'header' as version scheme.") resource.version_header_name = version_header_name if versioning_scheme == VersioningScheme.query: if version_query_name is None: raise RequiredArgumentMissingError( "Please specify version query name while using 'query' as version scheme.") resource.version_query_name = version_query_name return sdk_no_wait( no_wait, client.api_version_set.create_or_update, resource_group_name=resource_group_name, service_name=service_name, version_set_id=version_set_id, parameters=resource, if_match="*" if if_match is None else if_match)
Creates or Updates a Api Version Set.
apim_api_vs_create
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_vs_update( instance, versioning_scheme=None, description=None, display_name=None, version_header_name=None, version_query_name=None): """Updates the details of the Api VersionSet specified by its identifier.""" if display_name is not None: instance.display_name = display_name if versioning_scheme is not None: instance.versioning_scheme = versioning_scheme if versioning_scheme == VersioningScheme.header: if version_header_name is None: raise RequiredArgumentMissingError( "Please specify version header name while using 'header' as version scheme.") instance.version_header_name = version_header_name instance.version_query_name = None if versioning_scheme == VersioningScheme.query: if version_query_name is None: raise RequiredArgumentMissingError( "Please specify version query name while using 'query' as version scheme.") instance.version_query_name = version_query_name instance.version_header_name = None if description is None: instance.description = description return instance
Updates the details of the Api VersionSet specified by its identifier.
apim_api_vs_update
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_api_vs_delete(client, resource_group_name, service_name, version_set_id, if_match=None, no_wait=False): """Deletes specific Api Version Set.""" return sdk_no_wait( no_wait, client.api_version_set.delete, resource_group_name=resource_group_name, service_name=service_name, version_set_id=version_set_id, if_match="*" if if_match is None else if_match)
Deletes specific Api Version Set.
apim_api_vs_delete
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_ds_get(client, location, service_name): """Get specific soft-deleted Api Management Service.""" return client.deleted_services.get_by_name(service_name, location)
Get specific soft-deleted Api Management Service.
apim_ds_get
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_ds_list(client): """List soft-deleted Api Management Service.""" return client.deleted_services.list_by_subscription()
List soft-deleted Api Management Service.
apim_ds_list
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_ds_purge(client, service_name, location, no_wait=False): """Purge soft-deleted Api Management Service.""" return sdk_no_wait( no_wait, client.deleted_services.begin_purge, service_name=service_name, location=location)
Purge soft-deleted Api Management Service.
apim_ds_purge
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_graphql_resolver_create( client, resource_group_name, service_name, api_id, resolver_id, display_name, path, description=None, no_wait=False): """Creates a new Resolver. """ parameters = ResolverContract( display_name=display_name, path=path, description=description ) return sdk_no_wait(no_wait, client.graph_ql_api_resolver.create_or_update, resource_group_name=resource_group_name, service_name=service_name, api_id=api_id, resolver_id=resolver_id, parameters=parameters)
Creates a new Resolver.
apim_graphql_resolver_create
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_graphql_resolver_show(client, resource_group_name, service_name, api_id, resolver_id): """Shows details of a Resolver. """ return client.graph_ql_api_resolver.get( resource_group_name=resource_group_name, service_name=service_name, api_id=api_id, resolver_id=resolver_id)
Shows details of a Resolver.
apim_graphql_resolver_show
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_graphql_resolver_list(client, resource_group_name, service_name, api_id): """Lists a collection of Resolver. """ return client.graph_ql_api_resolver.list_by_api(resource_group_name, service_name, api_id)
Lists a collection of Resolver.
apim_graphql_resolver_list
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def apim_graphql_resolver_policy_create( client, resource_group_name, service_name, api_id, resolver_id, value_path, policy_format=None, no_wait=False): """Creates a new Resolver policy. """ api_file = open(value_path, 'r') content_value = api_file.read() value = content_value parameters = PolicyContract( format=policy_format, value=value ) return sdk_no_wait(no_wait, client.graph_ql_api_resolver_policy.create_or_update, resource_group_name=resource_group_name, service_name=service_name, api_id=api_id, resolver_id=resolver_id, policy_id="policy", parameters=parameters)
Creates a new Resolver policy.
apim_graphql_resolver_policy_create
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/custom.py
MIT
def _get_value_as_str(item, *args): """Get a nested value from a dict. :param dict item: The dict object """ try: for arg in args: item = item[arg] return str(item) if item else ' ' except (KeyError, TypeError, IndexError): return ' '
Get a nested value from a dict. :param dict item: The dict object
_get_value_as_str
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/_format.py
MIT
def _get_value_as_object(item, *args): """Get a nested value from a dict. :param dict item: The dict object """ try: for arg in args: item = item[arg] return item if item else ' ' except (KeyError, TypeError, IndexError): return ' '
Get a nested value from a dict. :param dict item: The dict object
_get_value_as_object
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/apim/_format.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/apim/_format.py
MIT
def check_name_availability(client, name): """Check the availability of a resource name. This is needed for resources where name is globally unique, such as a CDN endpoint. :param name: The resource name to validate. :type name: str """ validate_input = CheckNameAvailabilityInput(name=name, type=ResourceType.MICROSOFT_CDN_PROFILES_ENDPOINTS.value) return client.check_name_availability(validate_input)
Check the availability of a resource name. This is needed for resources where name is globally unique, such as a CDN endpoint. :param name: The resource name to validate. :type name: str
check_name_availability
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/cdn/custom/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/cdn/custom/custom.py
MIT
def flexible_server_threat_protection_get( client, resource_group_name, server_name): ''' Gets an advanced threat protection setting. ''' validate_resource_group(resource_group_name) return client.get( resource_group_name=resource_group_name, server_name=server_name, threat_protection_name="Default")
Gets an advanced threat protection setting.
flexible_server_threat_protection_get
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/rdbms/flexible_server_custom_postgres.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/rdbms/flexible_server_custom_postgres.py
MIT
def flexible_server_threat_protection_update( cmd, client, resource_group_name, server_name, state=None): # pylint: disable=unused-argument ''' Updates an advanced threat protection setting. Custom update function to apply parameters to instance. ''' validate_resource_group(resource_group_name) try: parameters = { 'properties': { 'state': state } } return resolve_poller( client.begin_create_or_update( resource_group_name=resource_group_name, server_name=server_name, threat_protection_name="Default", parameters=parameters), cmd.cli_ctx, 'PostgreSQL Flexible Server Advanced Threat Protection Setting Update') except HttpResponseError as ex: if "Operation returned an invalid status 'Accepted'" in ex.message: # TODO: Once the swagger is updated, this won't be needed. pass else: raise ex
Updates an advanced threat protection setting. Custom update function to apply parameters to instance.
flexible_server_threat_protection_update
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/rdbms/flexible_server_custom_postgres.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/rdbms/flexible_server_custom_postgres.py
MIT
def flexible_server_approve_private_endpoint_connection(cmd, client, resource_group_name, server_name, private_endpoint_connection_name, description=None): """Approve a private endpoint connection request for a server.""" validate_resource_group(resource_group_name) return _update_private_endpoint_connection_status( cmd, client, resource_group_name, server_name, private_endpoint_connection_name, is_approved=True, description=description)
Approve a private endpoint connection request for a server.
flexible_server_approve_private_endpoint_connection
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/rdbms/flexible_server_custom_postgres.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/rdbms/flexible_server_custom_postgres.py
MIT
def flexible_server_reject_private_endpoint_connection(cmd, client, resource_group_name, server_name, private_endpoint_connection_name, description=None): """Reject a private endpoint connection request for a server.""" validate_resource_group(resource_group_name) return _update_private_endpoint_connection_status( cmd, client, resource_group_name, server_name, private_endpoint_connection_name, is_approved=False, description=description)
Reject a private endpoint connection request for a server.
flexible_server_reject_private_endpoint_connection
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/rdbms/flexible_server_custom_postgres.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/rdbms/flexible_server_custom_postgres.py
MIT
def flexible_server_private_link_resource_get( client, resource_group_name, server_name): ''' Gets a private link resource for a PostgreSQL flexible server. ''' validate_resource_group(resource_group_name) return client.get( resource_group_name=resource_group_name, server_name=server_name, group_name="postgresqlServer")
Gets a private link resource for a PostgreSQL flexible server.
flexible_server_private_link_resource_get
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/rdbms/flexible_server_custom_postgres.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/rdbms/flexible_server_custom_postgres.py
MIT
def _get_resource_group_from_server_name(cli_ctx, server_name): """ Fetch resource group from server name :param str server_name: name of the server :return: resource group name or None :rtype: str """ client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_RDBMS).servers for server in client.list(): id_comps = parse_resource_id(server.id) if id_comps['name'] == server_name: return id_comps['resource_group'] return None
Fetch resource group from server name :param str server_name: name of the server :return: resource group name or None :rtype: str
_get_resource_group_from_server_name
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/rdbms/validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/rdbms/validators.py
MIT
def _validate_ip(ips): """ # Regex not working for re.(regex, '255.255.255.255'). Hence commenting it out for now regex = r'^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?).( 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?).( 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?).( 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)$' """ parsed_input = ips.split('-') if len(parsed_input) == 1: return _validate_ranges_in_ip(parsed_input[0]) if len(parsed_input) == 2: return _validate_ranges_in_ip(parsed_input[0]) and _validate_ranges_in_ip(parsed_input[1]) return False
# Regex not working for re.(regex, '255.255.255.255'). Hence commenting it out for now regex = r'^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?).( 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?).( 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?).( 25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)$'
_validate_ip
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/rdbms/validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/rdbms/validators.py
MIT
def approve_private_endpoint_connection(cmd, client, resource_group_name, server_name, private_endpoint_connection_name, description=None): """Approve a private endpoint connection request for a server.""" if isinstance(client, MySqlServersOperations): logger.warning(MYSQL_RETIRE_WARNING_MSG) elif isinstance(client, MariaDBServersOperations): logger.warning(MARIADB_RETIRE_WARNING_MSG) else: logger.warning(POSTGRESQL_RETIRE_WARNING_MSG) return _update_private_endpoint_connection_status( cmd, client, resource_group_name, server_name, private_endpoint_connection_name, is_approved=True, description=description)
Approve a private endpoint connection request for a server.
approve_private_endpoint_connection
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/rdbms/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/rdbms/custom.py
MIT
def reject_private_endpoint_connection(cmd, client, resource_group_name, server_name, private_endpoint_connection_name, description=None): """Reject a private endpoint connection request for a server.""" if isinstance(client, MySqlServersOperations): logger.warning(MYSQL_RETIRE_WARNING_MSG) elif isinstance(client, MariaDBServersOperations): logger.warning(MARIADB_RETIRE_WARNING_MSG) else: logger.warning(POSTGRESQL_RETIRE_WARNING_MSG) return _update_private_endpoint_connection_status( cmd, client, resource_group_name, server_name, private_endpoint_connection_name, is_approved=False, description=description)
Reject a private endpoint connection request for a server.
reject_private_endpoint_connection
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/rdbms/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/rdbms/custom.py
MIT
def server_key_create(client, resource_group_name, server_name, kid): """Create Server Key.""" if isinstance(client, MySqlServersOperations): logger.warning(MYSQL_RETIRE_WARNING_MSG) else: logger.warning(POSTGRESQL_RETIRE_WARNING_MSG) key_name = _get_server_key_name_from_uri(kid) parameters = { 'uri': kid, 'server_key_type': "AzureKeyVault" } return client.begin_create_or_update(server_name, key_name, resource_group_name, parameters)
Create Server Key.
server_key_create
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/rdbms/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/rdbms/custom.py
MIT
def server_key_get(client, resource_group_name, server_name, kid): """Get Server Key.""" if isinstance(client, MySqlServersOperations): logger.warning(MYSQL_RETIRE_WARNING_MSG) else: logger.warning(POSTGRESQL_RETIRE_WARNING_MSG) key_name = _get_server_key_name_from_uri(kid) return client.get( resource_group_name=resource_group_name, server_name=server_name, key_name=key_name)
Get Server Key.
server_key_get
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/rdbms/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/rdbms/custom.py
MIT
def server_key_delete(cmd, client, resource_group_name, server_name, kid): """Drop Server Key.""" if isinstance(client, MySqlServersOperations): logger.warning(MYSQL_RETIRE_WARNING_MSG) else: logger.warning(POSTGRESQL_RETIRE_WARNING_MSG) key_name = _get_server_key_name_from_uri(kid) return client.begin_delete( resource_group_name=resource_group_name, server_name=server_name, key_name=key_name)
Drop Server Key.
server_key_delete
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/rdbms/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/rdbms/custom.py
MIT
def _get_server_key_name_from_uri(uri): ''' Gets the key's name to use as a server key. The SQL server key API requires that the server key has a specific name based on the vault, key and key version. ''' match = re.match(r'https://(.)+\.(managedhsm.azure.net|managedhsm-preview.azure.net|vault.azure.net|vault-int.azure-int.net|vault.azure.cn|managedhsm.azure.cn|vault.usgovcloudapi.net|managedhsm.usgovcloudapi.net|vault.microsoftazure.de|managedhsm.microsoftazure.de|vault.cloudapi.eaglex.ic.gov|vault.cloudapi.microsoft.scloud)(:443)?\/keys/[^\/]+\/[0-9a-zA-Z]+$', uri) if match is None: raise CLIError('The provided uri is invalid. Please provide a valid Azure Key Vault key id. For example: ' '"https://YourVaultName.vault.azure.net/keys/YourKeyName/01234567890123456789012345678901" or "https://YourManagedHsmRegion.YourManagedHsmName.managedhsm.azure.net/keys/YourKeyName/01234567890123456789012345678901"') vault = uri.split('.')[0].split('/')[-1] key = uri.split('/')[-2] version = uri.split('/')[-1] return '{}_{}_{}'.format(vault, key, version)
Gets the key's name to use as a server key. The SQL server key API requires that the server key has a specific name based on the vault, key and key version.
_get_server_key_name_from_uri
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/rdbms/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/rdbms/custom.py
MIT
def server_ad_admin_set(client, resource_group_name, server_name, login=None, sid=None): ''' Sets a server's AD admin. ''' if isinstance(client, MySqlServersOperations): logger.warning(MYSQL_RETIRE_WARNING_MSG) else: logger.warning(POSTGRESQL_RETIRE_WARNING_MSG) parameters = { 'administratorType': 'ActiveDirectory', 'login': login, 'sid': sid, 'tenant_id': _get_tenant_id() } return client.begin_create_or_update( server_name=server_name, resource_group_name=resource_group_name, properties=parameters)
Sets a server's AD admin.
server_ad_admin_set
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/rdbms/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/rdbms/custom.py
MIT
def _get_tenant_id(): ''' Gets tenantId from current subscription. ''' profile = Profile() sub = profile.get_subscription() return sub['tenantId']
Gets tenantId from current subscription.
_get_tenant_id
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/rdbms/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/rdbms/custom.py
MIT
def __call__(self, parser, namespace, values, option_string=None): """ Parse a date value and return the ISO8601 string. """ import dateutil.parser import dateutil.tz value_string = ' '.join(values) dt_val = None try: # attempt to parse ISO 8601 dt_val = dateutil.parser.parse(value_string) except ValueError: pass # TODO: custom parsing attempts here if not dt_val: raise CLIError("Unable to parse: '{}'. Expected format: {}".format(value_string, help_string)) if dt_val.tzinfo: logger.warning('Timezone info will be ignored in %s.', value_string) dt_val = dt_val.replace(tzinfo=dateutil.tz.tzutc()) # Issue warning if any supplied time will be ignored if any([dt_val.hour, dt_val.minute, dt_val.second, dt_val.microsecond]): logger.warning('Time info will be set to midnight UTC for %s.', value_string) date_midnight = dt_val.replace(hour=0, minute=0, second=0, microsecond=0) format_string = date_midnight.isoformat() logger.info('Time info set to midnight UTC from %s to %s', value_string, format_string) setattr(namespace, self.dest, format_string)
Parse a date value and return the ISO8601 string.
get_date_midnight_type.__call__
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/monitor/actions.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/monitor/actions.py
MIT
def get_date_midnight_type(help=None): help_string = help + ' ' if help else '' accepted_formats = ['date (yyyy-mm-dd)', 'time (hh:mm:ss.xxxxx)', 'timezone (+/-hh:mm)'] help_string = help_string + 'Format: ' + ' '.join(accepted_formats) # pylint: disable=too-few-public-methods class DateAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): """ Parse a date value and return the ISO8601 string. """ import dateutil.parser import dateutil.tz value_string = ' '.join(values) dt_val = None try: # attempt to parse ISO 8601 dt_val = dateutil.parser.parse(value_string) except ValueError: pass # TODO: custom parsing attempts here if not dt_val: raise CLIError("Unable to parse: '{}'. Expected format: {}".format(value_string, help_string)) if dt_val.tzinfo: logger.warning('Timezone info will be ignored in %s.', value_string) dt_val = dt_val.replace(tzinfo=dateutil.tz.tzutc()) # Issue warning if any supplied time will be ignored if any([dt_val.hour, dt_val.minute, dt_val.second, dt_val.microsecond]): logger.warning('Time info will be set to midnight UTC for %s.', value_string) date_midnight = dt_val.replace(hour=0, minute=0, second=0, microsecond=0) format_string = date_midnight.isoformat() logger.info('Time info set to midnight UTC from %s to %s', value_string, format_string) setattr(namespace, self.dest, format_string) return CLIArgumentType(action=DateAction, nargs='+', help=help_string)
Parse a date value and return the ISO8601 string.
get_date_midnight_type
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/monitor/actions.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/monitor/actions.py
MIT
def build_autoscale_profile(autoscale_settings): """ Builds up a logical model of the autoscale weekly schedule. This then has to later be translated into objects that work with the Monitor autoscale API. """ from datetime import time import json from azure.mgmt.monitor.models import AutoscaleProfile def _validate_default_profile(default_profile, profile): if profile.capacity.default != default_profile.capacity.default or \ profile.capacity.minimum != default_profile.capacity.minimum or \ profile.capacity.maximum != default_profile.capacity.maximum: from knack.util import CLIError raise CLIError('unable to resolve default profile.') recurring_profiles = [x for x in autoscale_settings.profiles if x.recurrence] default_profiles = [x for x in autoscale_settings.profiles if not x.recurrence and not x.fixed_date] profile_schedule = { } # find the default profile and ensure that if there are multiple, they are consistent default_profile = default_profiles[0] if default_profiles else None for p in default_profiles: _validate_default_profile(default_profile, p) for profile in recurring_profiles: # portal creates extra default profiles with JSON names... # trying to stay compatible with that try: # portal-created "default" or end time json_name = json.loads(profile.name) sched_name = json_name['for'] end_time = time(hour=profile.recurrence.schedule.hours[0], minute=profile.recurrence.schedule.minutes[0]) if not default_profile: # choose this as default if it is the first default_profile = AutoscaleProfile( name='default', capacity=profile.capacity, rules=profile.rules ) else: # otherwise ensure it is consistent with the one chosen earlier _validate_default_profile(default_profile, profile) for day in profile.recurrence.schedule.days: if day not in profile_schedule: profile_schedule[day] = {} if sched_name in profile_schedule[day]: profile_schedule[day][sched_name]['end'] = end_time else: profile_schedule[day][sched_name] = {'end': end_time} except ValueError: # start time sched_name = profile.name start_time = time(hour=profile.recurrence.schedule.hours[0], minute=profile.recurrence.schedule.minutes[0]) for day in profile.recurrence.schedule.days: if day not in profile_schedule: profile_schedule[day] = {} if sched_name in profile_schedule[day]: profile_schedule[day][sched_name]['start'] = start_time profile_schedule[day][sched_name]['capacity'] = profile.capacity profile_schedule[day][sched_name]['rules'] = profile.rules else: profile_schedule[day][sched_name] = { 'start': start_time, 'capacity': profile.capacity, 'rules': profile.rules } return default_profile, profile_schedule
Builds up a logical model of the autoscale weekly schedule. This then has to later be translated into objects that work with the Monitor autoscale API.
build_autoscale_profile
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/monitor/_autoscale_util.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/monitor/_autoscale_util.py
MIT
def build_autoscale_profile_dict(autoscale_settings): """ Builds up a logical model of the autoscale weekly schedule. This then has to later be translated into objects that work with the Monitor autoscale API. """ from datetime import time import json def _validate_default_profile(default_profile, profile): if profile["capacity"]["default"] != default_profile["capacity"]["default"] or \ profile["capacity"]["minimum"] != default_profile["capacity"]["minimum"] or \ profile["capacity"]["maximum"] != default_profile["capacity"]["maximum"]: from knack.util import CLIError raise CLIError('unable to resolve default profile.') recurring_profiles = [x for x in autoscale_settings["profiles"] if x.get("recurrence", None)] default_profiles = [x for x in autoscale_settings["profiles"] if not x.get("recurrence", None) and not x.get("fixed_date", None)] profile_schedule = { } # find the default profile and ensure that if there are multiple, they are consistent default_profile = default_profiles[0] if default_profiles else None for p in default_profiles: _validate_default_profile(default_profile, p) for profile in recurring_profiles: # portal creates extra default profiles with JSON names... # trying to stay compatible with that try: # portal-created "default" or end time json_name = json.loads(profile["name"]) sched_name = json_name['for'] end_time = time(hour=profile["recurrence"]["schedule"]["hours"][0], minute=profile["recurrence"]["schedule"]["minutes"][0]) if not default_profile: # choose this as default if it is the first default_profile = { "name": 'default', "capacity": profile["capacity"], "rules": profile["rules"] } else: # otherwise ensure it is consistent with the one chosen earlier _validate_default_profile(default_profile, profile) for day in profile["recurrence"]["schedule"]["days"]: if day not in profile_schedule: profile_schedule[day] = {} if sched_name in profile_schedule[day]: profile_schedule[day][sched_name]['end'] = end_time else: profile_schedule[day][sched_name] = {'end': end_time} except ValueError: # start time sched_name = profile["name"] start_time = time(hour=profile["recurrence"]["schedule"]["hours"][0], minute=profile["recurrence"]["schedule"]["minutes"][0]) for day in profile["recurrence"]["schedule"]["days"]: if day not in profile_schedule: profile_schedule[day] = {} if sched_name in profile_schedule[day]: profile_schedule[day][sched_name]['start'] = start_time profile_schedule[day][sched_name]['capacity'] = profile["capacity"] profile_schedule[day][sched_name]['rules'] = profile["rules"] else: profile_schedule[day][sched_name] = { 'start': start_time, 'capacity': profile["capacity"], 'rules': profile["rules"] } return default_profile, profile_schedule
Builds up a logical model of the autoscale weekly schedule. This then has to later be translated into objects that work with the Monitor autoscale API.
build_autoscale_profile_dict
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/monitor/_autoscale_util.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/monitor/_autoscale_util.py
MIT
def validate_autoscale_profile_dict(schedule, start, end, recurrence): """ Check whether the proposed schedule conflicts with existing schedules. If so, issue a warning. """ # pylint: disable=cell-var-from-loop for day in recurrence["schedule"]["days"]: if day not in schedule: schedule[day] = {} def _find_conflicting_profile(time): conflict_sched = None for sched_name, sched_values in schedule[day].items(): if sched_values['start'] <= time <= sched_values['end']: conflict_sched = sched_name return conflict_sched def _profile_is_subset(profile, start, end): return profile['start'] >= start and profile['end'] <= end # check if start or end dates fall within an existing schedule # check is proposed schedule engulfs any existing schedules profile_conflicts = [k for k, v in schedule[day].items() if _profile_is_subset(v, start, end)] start_conflict = _find_conflicting_profile(start) if start_conflict: profile_conflicts.append(start_conflict) end_conflict = _find_conflicting_profile(end) if end_conflict: profile_conflicts.append(end_conflict) if profile_conflicts: logger.warning("Proposed schedule '%s %s-%s' has a full or partial overlap with the following existing " "schedules: %s. Unexpected behavior may occur.", day, start, end, ', '.join(profile_conflicts))
Check whether the proposed schedule conflicts with existing schedules. If so, issue a warning.
validate_autoscale_profile_dict
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/monitor/_autoscale_util.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/monitor/_autoscale_util.py
MIT
def _validate_tags(namespace): """ Extracts multiple space-separated tags in key[=value] format """ if isinstance(namespace.tags, list): tags_dict = {} for item in namespace.tags: tags_dict.update(_validate_tag(item)) namespace.tags = tags_dict
Extracts multiple space-separated tags in key[=value] format
_validate_tags
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/monitor/validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/monitor/validators.py
MIT
def _validate_tag(string): """ Extracts a single tag in key[=value] format """ result = {} if string: comps = string.split('=', 1) result = {comps[0]: comps[1]} if len(comps) > 1 else {string: ''} return result
Extracts a single tag in key[=value] format
_validate_tag
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/monitor/validators.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/monitor/validators.py
MIT
def _activity_log_select_filter_builder(events=None): """Build up select filter string from events""" if events: return ' , '.join(events) return None
Build up select filter string from events
_activity_log_select_filter_builder
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/monitor/custom.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/monitor/custom.py
MIT
def _build_arguments_schema(cls, *args, **kwargs): args_schema = super()._build_arguments_schema(*args, **kwargs) args_schema.notifications._registered = False args_schema.profiles._registered = False args_schema.target_resource_location._registered = False args_schema.target_resource_uri._registered = False args_schema.count = AAZIntArg( options=["--count"], help='The numer of instances to use. If used with --min/max-count, the default number of instances to use.', arg_group="Instance Limit", ) args_schema.min_count = AAZIntArg( options=["--min-count"], help='The minimum number of instances.', arg_group="Instance Limit", ) args_schema.max_count = AAZIntArg( options=["--max-count"], help='The maximum number of instances.', arg_group="Instance Limit", ) args_schema.add_actions = AAZCustomListArg( options=["--add-actions"], singular_options=['--add-action', '-a'], help="Add an action to fire when a scaling event occurs." + ''' Usage: --add-action TYPE KEY [ARG ...] Email: --add-action email [email protected] [email protected] Webhook: --add-action webhook https://www.contoso.com/alert apiKey=value Webhook: --add-action webhook https://www.contoso.com/alert?apiKey=value Multiple actions can be specified by using more than one `--add-action` argument. ''', arg_group="Notification", ) args_schema.add_actions.Element = AAZCustomListArg() args_schema.add_actions.Element.Element = AAZStrArg() args_schema.remove_actions = AAZCustomListArg( options=["--remove-actions"], singular_options=['--remove-action', '-r'], help="Remove one or more actions." + ''' Usage: --remove-action TYPE KEY [KEY ...] Email: --remove-action email [email protected] [email protected] Webhook: --remove-action webhook https://contoso.com/alert https://alerts.contoso.com. ''', arg_group="Notification", ) args_schema.remove_actions.Element = AAZCustomListArg() args_schema.remove_actions.Element.Element = AAZStrArg() args_schema.email_administrator = AAZBoolArg( options=["--email-administrator"], help='Send email to subscription administrator on scaling.', arg_group="Notification", ) args_schema.email_coadministrators = AAZBoolArg( options=["--email-coadministrators"], help='Send email to subscription co-administrators on scaling.', arg_group="Notification", ) return args_schema
, arg_group="Notification", ) args_schema.add_actions.Element = AAZCustomListArg() args_schema.add_actions.Element.Element = AAZStrArg() args_schema.remove_actions = AAZCustomListArg( options=["--remove-actions"], singular_options=['--remove-action', '-r'], help="Remove one or more actions." +
_build_arguments_schema
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/monitor/operations/autoscale_settings.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/monitor/operations/autoscale_settings.py
MIT
def _parse_action_removals(actions): """ Separates the combined list of keys to remove into webhooks and emails. """ flattened = list({x for sublist in actions for x in sublist}) emails = [] webhooks = [] for item in flattened: if item.startswith('http://') or item.startswith('https://'): webhooks.append(item) else: emails.append(item) return emails, webhooks
Separates the combined list of keys to remove into webhooks and emails.
_parse_action_removals
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/monitor/operations/autoscale_settings.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/monitor/operations/autoscale_settings.py
MIT
def _build_arguments_schema(cls, *args, **kwargs): args_schema = super()._build_arguments_schema(*args, **kwargs) args_schema.enabled._registered = False args_schema.location._registered = False args_schema.action_groups._registered = False args_schema.scopes._registered = False args_schema.scope_ui = AAZListArg( options=["--scope", "-s"], help="A list of strings that will be used as prefixes." + ''' The alert rule will only apply to activity logs with resourceIDs that fall under one of these prefixes. If not provided, the subscriptionId will be used. ''', ) args_schema.scope_ui.Element = AAZStrArg() args_schema.disable = AAZBoolArg( options=["--disable"], help="Disable the activity log alert rule after it is created.", default=False, ) args_schema.condition = AAZCustomListArg( options=["--condition", "-c"], help="The condition that will cause the alert rule to activate. " "The format is FIELD=VALUE[ and FIELD=VALUE...]" + ''' The possible values for the field are 'resourceId', 'category', 'caller', 'level', 'operationName', 'resourceGroup', 'resourceProvider', 'status', 'subStatus', 'resourceType', or anything beginning with 'properties'. ''' ) args_schema.condition.Element = AAZStrArg() args_schema.action_group_ids = AAZListArg( options=["--action-group", "-a"], help="Add an action group. Accepts space-separated action group identifiers. " "The identifier can be the action group's name or its resource ID.", ) args_schema.action_group_ids.Element = AAZResourceIdArg( fmt=AAZResourceIdArgFormat( template="/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/microsoft.insights/actionGroups/{}", ) ) args_schema.webhook_properties_list = AAZCustomListArg( options=['--webhook-properties', '-w'], help="Space-separated webhook properties in 'key[=value]' format. " "These properties are associated with the action groups added in this command." + ''' For any webhook receiver in these action group, this data is appended to the webhook payload. To attach different webhook properties to different action groups, add the action groups in separate update-action commands. ''' ) args_schema.webhook_properties_list.Element = AAZStrArg() return args_schema
, ) args_schema.scope_ui.Element = AAZStrArg() args_schema.disable = AAZBoolArg( options=["--disable"], help="Disable the activity log alert rule after it is created.", default=False, ) args_schema.condition = AAZCustomListArg( options=["--condition", "-c"], help="The condition that will cause the alert rule to activate. " "The format is FIELD=VALUE[ and FIELD=VALUE...]" +
_build_arguments_schema
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/monitor/operations/activity_log_alerts.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/monitor/operations/activity_log_alerts.py
MIT
def _normalize_names(cli_ctx, resource_names, resource_group, namespace, resource_type): """Normalize a group of resource names. Returns a set of resource ids. Throws if any of the name can't be correctly converted to a resource id.""" from azure.mgmt.core.tools import is_valid_resource_id, resource_id from azure.cli.core.commands.client_factory import get_subscription_id rids = set() # normalize the action group ids for name in resource_names: if is_valid_resource_id(name): rids.add(name) else: rid = resource_id(subscription=get_subscription_id(cli_ctx), resource_group=resource_group, namespace=namespace, type=resource_type, name=name) if not is_valid_resource_id(rid): raise ValueError('The resource name {} is not valid.'.format(name)) rids.add(rid) return rids
Normalize a group of resource names. Returns a set of resource ids. Throws if any of the name can't be correctly converted to a resource id.
_normalize_names
python
Azure/azure-cli
src/azure-cli/azure/cli/command_modules/monitor/operations/activity_log_alerts.py
https://github.com/Azure/azure-cli/blob/master/src/azure-cli/azure/cli/command_modules/monitor/operations/activity_log_alerts.py
MIT