How to use the knack.util.CLIError function in knack

To help you get started, we’ve selected a few knack examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Azure / azure-cli / src / azure-cli / azure / cli / command_modules / cosmosdb / _exception_handler.py View on Github external
def network_exception_handler(ex):
    # wraps a connection exception in CLIError
    import requests.exceptions
    if isinstance(ex, (requests.exceptions.ConnectionError, requests.exceptions.HTTPError)):
        raise CLIError('Please ensure you have network connection. Error detail: ' + str(ex))
    raise ex
github Azure / azure-cli-extensions / src / support / azext_support / _validators.py View on Github external
def _validate_communication_name(cmd, ticket_name, communication_name):
    client = cf_communications(cmd.cli_ctx)
    rsp = client.check_name_availability(support_ticket_name=ticket_name, name=communication_name,
                                         type="Microsoft.Support/communications")
    if not rsp.name_available:
        raise CLIError(rsp.message)
github Azure / azure-cli / src / azure-cli / azure / cli / command_modules / vm / _validators.py View on Github external
def _validate_vm_vmss_msi(cmd, namespace, from_set_command=False):
    if from_set_command or namespace.assign_identity is not None:
        identities = namespace.assign_identity or []
        from ._vm_utils import MSI_LOCAL_ID
        for i, _ in enumerate(identities):
            if identities[i] != MSI_LOCAL_ID:
                identities[i] = _get_resource_id(cmd.cli_ctx, identities[i], namespace.resource_group_name,
                                                 'userAssignedIdentities', 'Microsoft.ManagedIdentity')
        if not namespace.identity_scope and getattr(namespace.identity_role, 'is_default', None) is None:
            raise CLIError("usage error: '--role {}' is not applicable as the '--scope' is not provided".format(
                namespace.identity_role))
        user_assigned_identities = [x for x in identities if x != MSI_LOCAL_ID]
        if user_assigned_identities and not cmd.supported_api_version(min_api='2017-12-01'):
            raise CLIError('usage error: user assigned identity is only available under profile '
                           'with minimum Compute API version of 2017-12-01')
        if namespace.identity_scope:
            if identities and MSI_LOCAL_ID not in identities:
                raise CLIError("usage error: '--scope'/'--role' is only applicable when assign system identity")
            # keep 'identity_role' for output as logical name is more readable
            setattr(namespace, 'identity_role_id', _resolve_role_id(cmd.cli_ctx, namespace.identity_role,
                                                                    namespace.identity_scope))
    elif namespace.identity_scope or getattr(namespace.identity_role, 'is_default', None) is None:
        raise CLIError('usage error: --assign-identity [--scope SCOPE] [--role ROLE]')
github Azure / azure-devops-cli-extension / azure-devops / azext_devops / dev / pipelines / pipeline_create_helpers / azure_repos_helper.py View on Github external
def _checkin_files_to_azure_repo(files, repo_name, branch, organization, project,
                                 message):
    if files:
        for file in files:
            _checkin_file_to_azure_repo(file.path, file.content, repo_name, branch, organization, project, message)
    else:
        raise CLIError("No files to checkin.")
github Azure / azure-cli / src / azure-cli / azure / cli / command_modules / acr / _utils.py View on Github external
def remove_timer_trigger(task_name,
                         timer_name,
                         timer_triggers):
    """Remove the timer trigger from the list of existing timer triggers for a task.
    :param str task_name: The name of the task
    :param str timer_name: The name of the timer trigger to be removed
    :param str timer_triggers: The list of existing timer_triggers for a task
    """

    if not timer_triggers:
        raise CLIError("No timer triggers exist for the task '{}'.".format(task_name))

    # Check that the timer trigger exists in the list and if not exit
    if any(timer.name == timer_name for timer in timer_triggers):
        for timer in timer_triggers:
            if timer.name == timer_name:
                timer_triggers.remove(timer)
    else:
        raise CLIError("The timer '{}' does not exist for the task '{}'.".format(timer_name, task_name))

    return timer_triggers
github Azure / azure-cli / src / azure-cli / azure / cli / command_modules / monitor / operations / activity_log_alerts.py View on Github external
def _get_alert_settings(client, resource_group_name, activity_log_alert_name, throw_if_missing=True):
    from azure.mgmt.monitor.v2017_04_01.models import ErrorResponseException

    try:
        return client.get(resource_group_name=resource_group_name, activity_log_alert_name=activity_log_alert_name)
    except ErrorResponseException as ex:
        from knack.util import CLIError
        if ex.response.status_code == 404:
            if throw_if_missing:
                raise CLIError('Can\'t find activity log alert {} in resource group {}.'.format(activity_log_alert_name,
                                                                                                resource_group_name))
            return None
        raise CLIError(ex.message)
github Azure / azure-cli / src / azure-cli / azure / cli / command_modules / network / _validators.py View on Github external
def _validate_name_or_id(value, resource_type):
        if not is_valid_resource_id(value):
            subscription = getattr(namespace, 'subscription', get_subscription_id(cmd.cli_ctx))
            return resource_id(
                subscription=subscription,
                resource_group=namespace.resource_group_name,
                namespace='Microsoft.Network',
                type=resource_type,
                name=value)
        return value

    if (namespace.local_gateway2 or namespace.vnet_gateway2) and not namespace.shared_key:
        raise CLIError('--shared-key is required for VNET-to-VNET or Site-to-Site connections.')

    if namespace.express_route_circuit2 and namespace.shared_key:
        raise CLIError('--shared-key cannot be used with an ExpressRoute connection.')

    namespace.vnet_gateway1 = \
        _validate_name_or_id(namespace.vnet_gateway1, 'virtualNetworkGateways')

    if namespace.express_route_circuit2:
        namespace.express_route_circuit2 = \
            _validate_name_or_id(
                namespace.express_route_circuit2, 'expressRouteCircuits')
        namespace.connection_type = 'ExpressRoute'
    elif namespace.local_gateway2:
        namespace.local_gateway2 = \
            _validate_name_or_id(namespace.local_gateway2, 'localNetworkGateways')
        namespace.connection_type = 'IPSec'
    elif namespace.vnet_gateway2:
        namespace.vnet_gateway2 = \
            _validate_name_or_id(namespace.vnet_gateway2, 'virtualNetworkGateways')
github Azure / azure-cli / src / azure-cli / azure / cli / command_modules / appservice / azure_devops_build_interactive.py View on Github external
project_name=self.project_name,
                    build_id=self.build.id,
                    prev_log=prev_log_status,
                    curr_log=curr_log_status
                )
                if log_content:
                    self.logger.info(log_content)
                prev_log_status = curr_log_status

        if build.result == 'failed':
            url = "https://dev.azure.com/{org}/{proj}/_build/results?buildId={build_id}".format(
                org=self.organization_name,
                proj=self.project_name,
                build_id=build.id
            )
            raise CLIError("Sorry, your build has failed in Azure Pipelines.{ls}"
                           "To view details on why your build has failed please visit {url}".format(
                               url=url, ls=os.linesep
                           ))
        if build.result == 'succeeded':
            self.logger.warning("Your build has completed.")
github Azure / azure-cli-dev-tools / azdev / operations / help / __init__.py View on Github external
def _set_profile(profile):
    try:
        _logger.warning("Setting the CLI profile to '%s'", profile)
        check_call(['az', 'cloud', 'update', '--profile', profile])
    except CalledProcessError as e:
        raise CLIError("Failed to set profile {} due to err:\n{}\n"
                       "Please check that your profile is set to the expected value.".format(profile, e))
github Azure / azure-cli / src / azure-cli / azure / cli / command_modules / acr / custom.py View on Github external
from subprocess import PIPE, Popen, CalledProcessError
    try:
        p = Popen([docker_command, "ps"], stdout=PIPE, stderr=PIPE)
        _, stderr = p.communicate()
    except OSError as e:
        logger.debug("Could not run '%s' command. Exception: %s", docker_command, str(e))
        # The executable may not be discoverable in WSL so retry *.exe once
        try:
            docker_command = 'docker.exe'
            p = Popen([docker_command, "ps"], stdout=PIPE, stderr=PIPE)
            _, stderr = p.communicate()
        except OSError as inner:
            logger.debug("Could not run '%s' command. Exception: %s", docker_command, str(inner))
            if is_diagnostics_context:
                return None, DOCKER_COMMAND_ERROR
            raise CLIError(DOCKER_COMMAND_ERROR.get_error_message())
        except CalledProcessError as inner:
            logger.debug("Could not run '%s' command. Exception: %s", docker_command, str(inner))
            if is_diagnostics_context:
                return docker_command, DOCKER_DAEMON_ERROR
            raise CLIError(DOCKER_DAEMON_ERROR.get_error_message())
    except CalledProcessError as e:
        logger.debug("Could not run '%s' command. Exception: %s", docker_command, str(e))
        if is_diagnostics_context:
            return docker_command, DOCKER_DAEMON_ERROR
        raise CLIError(DOCKER_DAEMON_ERROR.get_error_message())

    if stderr:
        if is_diagnostics_context:
            return None, DOCKER_COMMAND_ERROR.set_error_message(stderr.decode())
        raise CLIError(DOCKER_COMMAND_ERROR.set_error_message(stderr.decode()).get_error_message())