Example #1
0
def validate_diagnostic_settings(cmd, namespace):
    from azure.cli.core.commands.client_factory import get_subscription_id
    from msrestazure.tools import is_valid_resource_id, resource_id
    from knack.util import CLIError
    resource_group_error = "--resource-group is required when name is provided for storage account or workspace or " \
                           "service bus namespace and rule. "

    get_target_resource_validator('resource_uri', required=True, preserve_resource_group_parameter=True)(cmd, namespace)

    if namespace.storage_account and not is_valid_resource_id(namespace.storage_account):
        if namespace.resource_group_name is None:
            raise CLIError(resource_group_error)
        namespace.storage_account = resource_id(subscription=get_subscription_id(cmd.cli_ctx),
                                                resource_group=namespace.resource_group_name,
                                                namespace='microsoft.Storage',
                                                type='storageAccounts',
                                                name=namespace.storage_account)

    if namespace.workspace and not is_valid_resource_id(namespace.workspace):
        if namespace.resource_group_name is None:
            raise CLIError(resource_group_error)
        namespace.workspace = resource_id(subscription=get_subscription_id(cmd.cli_ctx),
                                          resource_group=namespace.resource_group_name,
                                          namespace='microsoft.OperationalInsights',
                                          type='workspaces',
                                          name=namespace.workspace)

    if not namespace.storage_account and not namespace.workspace and not namespace.event_hub:
        raise CLIError(
            'One of the following parameters is expected: --storage-account, --event-hub-name, or --workspace.')

    try:
        del namespace.resource_group_name
    except AttributeError:
        pass
Example #2
0
def process_nw_test_connectivity_namespace(cmd, namespace):
    from msrestazure.tools import is_valid_resource_id, resource_id, parse_resource_id

    compute_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_COMPUTE).virtual_machines
    vm_name = parse_resource_id(namespace.source_resource)['name']
    rg = namespace.resource_group_name or parse_resource_id(namespace.source_resource).get('resource_group', None)
    if not rg:
        raise CLIError('usage error: --source-resource ID | --source-resource NAME --resource-group NAME')
    vm = compute_client.get(rg, vm_name)
    namespace.location = vm.location  # pylint: disable=no-member
    get_network_watcher_from_location(remove=True)(cmd, namespace)

    if namespace.source_resource and not is_valid_resource_id(namespace.source_resource):
        namespace.source_resource = resource_id(
            subscription=get_subscription_id(cmd.cli_ctx),
            resource_group=rg,
            namespace='Microsoft.Compute',
            type='virtualMachines',
            name=namespace.source_resource)

    if namespace.dest_resource and not is_valid_resource_id(namespace.dest_resource):
        namespace.dest_resource = resource_id(
            subscription=get_subscription_id(cmd.cli_ctx),
            resource_group=namespace.resource_group_name,
            namespace='Microsoft.Compute',
            type='virtualMachines',
            name=namespace.dest_resource)
Example #3
0
    def _validator(cmd, namespace):
        from msrestazure.tools import is_valid_resource_id
        from knack.util import CLIError
        name_or_id = getattr(namespace, dest)
        rg = namespace.resource_group_name
        res_ns = namespace.namespace
        parent = namespace.parent
        res_type = namespace.resource_type

        usage_error = CLIError('usage error: --{0} ID | --{0} NAME --resource-group NAME '
                               '--{0}-type TYPE [--{0}-parent PARENT] '
                               '[--{0}-namespace NAMESPACE]'.format(alias))
        if not name_or_id and required:
            raise usage_error
        elif name_or_id:
            if is_valid_resource_id(name_or_id) and any((res_ns, parent, res_type)):
                raise usage_error
            elif not is_valid_resource_id(name_or_id):
                from azure.cli.core.commands.client_factory import get_subscription_id
                if res_type and '/' in res_type:
                    res_ns = res_ns or res_type.rsplit('/', 1)[0]
                    res_type = res_type.rsplit('/', 1)[1]
                if not all((rg, res_ns, res_type, name_or_id)):
                    raise usage_error

                setattr(namespace, dest,
                        '/subscriptions/{}/resourceGroups/{}/providers/{}/{}{}/{}'.format(
                            get_subscription_id(cmd.cli_ctx), rg, res_ns, parent + '/' if parent else '',
                            res_type, name_or_id))

        del namespace.namespace
        del namespace.parent
        del namespace.resource_type
        if not preserve_resource_group_parameter:
            del namespace.resource_group_name
Example #4
0
def process_nw_packet_capture_create_namespace(cmd, namespace):
    from msrestazure.tools import is_valid_resource_id, resource_id
    get_network_watcher_from_vm(cmd, namespace)

    storage_usage = CLIError('usage error: --storage-account NAME_OR_ID [--storage-path '
                             'PATH] [--file-path PATH] | --file-path PATH')
    if not namespace.storage_account and not namespace.file_path:
        raise storage_usage

    if namespace.storage_path and not namespace.storage_account:
        raise storage_usage

    if not is_valid_resource_id(namespace.vm):
        namespace.vm = resource_id(
            subscription=get_subscription_id(cmd.cli_ctx),
            resource_group=namespace.resource_group_name,
            namespace='Microsoft.Compute',
            type='virtualMachines',
            name=namespace.vm)

    if namespace.storage_account and not is_valid_resource_id(namespace.storage_account):
        namespace.storage_account = resource_id(
            subscription=get_subscription_id(cmd.cli_ctx),
            resource_group=namespace.resource_group_name,
            namespace='Microsoft.Storage',
            type='storageAccounts',
            name=namespace.storage_account)

    if namespace.file_path:
        file_path = namespace.file_path
        if not file_path.endswith('.cap'):
            raise CLIError("usage error: --file-path PATH must end with the '*.cap' extension")
        file_path = file_path.replace('/', '\\')
        namespace.file_path = file_path
    def test_update_artifacts(self):
        result = _update_artifacts([], self.lab_resource_id)
        assert result == []

        result = _update_artifacts([self.jdk_artifact], self.lab_resource_id)
        for artifact in result:
            assert is_valid_resource_id(artifact.get('artifact_id'))
            self.assertEqual('{}{}'.format(self.lab_resource_id,
                                           self.jdk_artifact.get('artifact_id')),
                             artifact.get('artifact_id'))

        result = _update_artifacts([self.jdk_artifact, self.apt_get_artifact],
                                   self.lab_resource_id)
        for artifact in result:
            assert is_valid_resource_id(artifact.get('artifact_id'))

        result = _update_artifacts([self.full_artifact, self.apt_get_artifact],
                                   self.lab_resource_id)
        for artifact in result:
            assert is_valid_resource_id(artifact.get('artifact_id'))
            self.assertEqual(artifact.get('artifact_id'), self.full_artifact.get('artifact_id'))

        with self.assertRaises(CLIError):
            _update_artifacts({}, self.lab_resource_id)

        invalid_artifact = self.jdk_artifact
        del invalid_artifact['artifact_id']
        with self.assertRaises(CLIError):
            _update_artifacts([invalid_artifact], self.lab_resource_id)
Example #6
0
def validate_diagnostic_settings(cmd, namespace):
    from azure.cli.core.commands.client_factory import get_subscription_id
    from msrestazure.tools import is_valid_resource_id, resource_id, parse_resource_id
    from knack.util import CLIError

    get_target_resource_validator('resource_uri', required=True, preserve_resource_group_parameter=True)(cmd, namespace)
    if not namespace.resource_group_name:
        namespace.resource_group_name = parse_resource_id(namespace.resource_uri)['resource_group']

    if namespace.storage_account and not is_valid_resource_id(namespace.storage_account):
        namespace.storage_account = resource_id(subscription=get_subscription_id(cmd.cli_ctx),
                                                resource_group=namespace.resource_group_name,
                                                namespace='microsoft.Storage',
                                                type='storageAccounts',
                                                name=namespace.storage_account)

    if namespace.workspace and not is_valid_resource_id(namespace.workspace):
        namespace.workspace = resource_id(subscription=get_subscription_id(cmd.cli_ctx),
                                          resource_group=namespace.resource_group_name,
                                          namespace='microsoft.OperationalInsights',
                                          type='workspaces',
                                          name=namespace.workspace)

    if namespace.event_hub and is_valid_resource_id(namespace.event_hub):
        namespace.event_hub = parse_resource_id(namespace.event_hub)['name']

    if namespace.event_hub_rule:
        if not is_valid_resource_id(namespace.event_hub_rule):
            if not namespace.event_hub:
                raise CLIError('usage error: --event-hub-rule ID | --event-hub-rule NAME --event-hub NAME')
            # use value from --event-hub if the rule is a name
            namespace.event_hub_rule = resource_id(
                subscription=get_subscription_id(cmd.cli_ctx),
                resource_group=namespace.resource_group_name,
                namespace='Microsoft.EventHub',
                type='namespaces',
                name=namespace.event_hub,
                child_type_1='AuthorizationRules',
                child_name_1=namespace.event_hub_rule)
        elif not namespace.event_hub:
            # extract the event hub name from `--event-hub-rule` if provided as an ID
            namespace.event_hub = parse_resource_id(namespace.event_hub_rule)['name']

    if not any([namespace.storage_account, namespace.workspace, namespace.event_hub]):
        raise CLIError(
            'usage error - expected one or more:  --storage-account NAME_OR_ID | --workspace NAME_OR_ID '
            '| --event-hub NAME_OR_ID | --event-hub-rule ID')

    try:
        del namespace.resource_group_name
    except AttributeError:
        pass
Example #7
0
def process_ag_listener_create_namespace(cmd, namespace):  # pylint: disable=unused-argument
    from msrestazure.tools import is_valid_resource_id
    if namespace.frontend_ip and not is_valid_resource_id(namespace.frontend_ip):
        namespace.frontend_ip = _generate_ag_subproperty_id(
            cmd.cli_ctx, namespace, 'frontendIpConfigurations', namespace.frontend_ip)

    if namespace.frontend_port and not is_valid_resource_id(namespace.frontend_port):
        namespace.frontend_port = _generate_ag_subproperty_id(
            cmd.cli_ctx, namespace, 'frontendPorts', namespace.frontend_port)

    if namespace.ssl_cert and not is_valid_resource_id(namespace.ssl_cert):
        namespace.ssl_cert = _generate_ag_subproperty_id(
            cmd.cli_ctx, namespace, 'sslCertificates', namespace.ssl_cert)
Example #8
0
def process_ag_url_path_map_rule_create_namespace(cmd, namespace):  # pylint: disable=unused-argument
    from msrestazure.tools import is_valid_resource_id
    if namespace.address_pool and not is_valid_resource_id(namespace.address_pool):
        namespace.address_pool = _generate_ag_subproperty_id(
            cmd.cli_ctx, namespace, 'backendAddressPools', namespace.address_pool)

    if namespace.http_settings and not is_valid_resource_id(namespace.http_settings):
        namespace.http_settings = _generate_ag_subproperty_id(
            cmd.cli_ctx, namespace, 'backendHttpSettingsCollection', namespace.http_settings)

    if namespace.redirect_config and not is_valid_resource_id(
            namespace.redirect_config):
        namespace.redirect_config = _generate_ag_subproperty_id(
            cmd.cli_ctx, namespace, 'redirectConfigurations', namespace.redirect_config)
Example #9
0
def validate_resource(cmd, namespace):  # pylint: disable=unused-argument
    if namespace.resource:
        if not is_valid_resource_id(namespace.resource):
            if not namespace.namespace:
                raise CLIError('--namespace is required if --resource is not a resource ID.')
            if not namespace.resource_type:
                raise CLIError('--resource-type is required if --resource is not a resource ID.')
Example #10
0
def get_storage_account_endpoint(cmd, storage_account, is_wasb):
    from ._client_factory import cf_storage
    from msrestazure.tools import parse_resource_id, is_valid_resource_id
    host = None
    if is_valid_resource_id(storage_account):
        parsed_storage_account = parse_resource_id(storage_account)
        resource_group_name = parsed_storage_account['resource_group']
        storage_account_name = parsed_storage_account['resource_name']

        storage_client = cf_storage(cmd.cli_ctx)
        storage_account = storage_client.storage_accounts.get_properties(
            resource_group_name=resource_group_name,
            account_name=storage_account_name)

        def extract_endpoint(storage_account, is_wasb):
            if not storage_account:
                return None
            return storage_account.primary_endpoints.dfs if not is_wasb else storage_account.primary_endpoints.blob

        def extract_host(uri):
            import re
            return uri and re.search('//(.*)/', uri).groups()[0]

        host = extract_host(extract_endpoint(storage_account, is_wasb))
    return host
Example #11
0
def parse_domain_name(domain):
    from msrestazure.tools import parse_resource_id, is_valid_resource_id
    domain_name = None
    if is_valid_resource_id(domain):
        parsed_domain_id = parse_resource_id(domain)
        domain_name = parsed_domain_id['resource_name']
    return domain_name
Example #12
0
def _use_custom_image(cli_ctx, namespace):
    """ Retrieve custom image from lab and update namespace """
    from msrestazure.tools import is_valid_resource_id
    if is_valid_resource_id(namespace.image):
        namespace.custom_image_id = namespace.image
    else:
        custom_image_operation = get_devtestlabs_management_client(cli_ctx, None).custom_images
        odata_filter = ODATA_NAME_FILTER.format(namespace.image)
        custom_images = list(custom_image_operation.list(namespace.resource_group_name,
                                                         namespace.lab_name,
                                                         filter=odata_filter))
        if not custom_images:
            err = "Unable to find custom image name '{}' in the '{}' lab.".format(namespace.image, namespace.lab_name)
            raise CLIError(err)
        elif len(custom_images) > 1:
            err = "Found more than 1 image with name '{}'. Please pick one from {}"
            raise CLIError(err.format(namespace.image, [x.name for x in custom_images]))
        else:
            namespace.custom_image_id = custom_images[0].id

            if custom_images[0].vm is not None:
                if custom_images[0].vm.windows_os_info is not None:
                    os_type = "Windows"
                else:
                    os_type = "Linux"
            elif custom_images[0].vhd is not None:
                os_type = custom_images[0].vhd.os_type
            else:
                raise CLIError("OS type cannot be inferred from the custom image {}".format(custom_images[0].id))

            namespace.os_type = os_type
Example #13
0
    def simple_validator(cmd, namespace):
        if namespace.virtual_network_name is None and namespace.subnet is None:
            return
        if namespace.subnet == '':
            return
        usage_error = ValueError('incorrect usage: ( --subnet ID | --subnet NAME --vnet-name NAME)')
        # error if vnet-name is provided without subnet
        if namespace.virtual_network_name and not namespace.subnet:
            raise usage_error

        # determine if subnet is name or ID
        is_id = is_valid_resource_id(namespace.subnet)

        # error if vnet-name is provided along with a subnet ID
        if is_id and namespace.virtual_network_name:
            raise usage_error
        elif not is_id and not namespace.virtual_network_name:
            raise usage_error

        if not is_id:
            namespace.subnet = resource_id(
                subscription=get_subscription_id(cmd.cli_ctx),
                resource_group=namespace.resource_group_name,
                namespace='Microsoft.Network',
                type='virtualNetworks',
                name=namespace.virtual_network_name,
                child_type_1='subnets',
                child_name_1=namespace.subnet)
Example #14
0
def _validate_name_or_id(
        cli_ctx, resource_group_name, property_value, property_type, parent_value, parent_type):
    from azure.cli.core.commands.client_factory import get_subscription_id
    from msrestazure.tools import parse_resource_id, is_valid_resource_id
    has_parent = parent_type is not None
    if is_valid_resource_id(property_value):
        resource_id_parts = parse_resource_id(property_value)
        value_supplied_was_id = True
    elif has_parent:
        resource_id_parts = dict(
            name=parent_value,
            resource_group=resource_group_name,
            namespace=parent_type.split('/')[0],
            type=parent_type.split('/')[1],
            subscription=get_subscription_id(cli_ctx),
            child_name_1=property_value,
            child_type_1=property_type)
        value_supplied_was_id = False
    else:
        resource_id_parts = dict(
            name=property_value,
            resource_group=resource_group_name,
            namespace=property_type.split('/')[0],
            type=property_type.split('/')[1],
            subscription=get_subscription_id(cli_ctx))
        value_supplied_was_id = False
    return (resource_id_parts, value_supplied_was_id)
Example #15
0
def _replica_create(cmd, client, resource_group_name, server_name, source_server, no_wait=False, **kwargs):
    provider = 'Microsoft.DBForMySQL' if isinstance(client, MySqlServersOperations) else 'Microsoft.DBforPostgreSQL'
    # set source server id
    if not is_valid_resource_id(source_server):
        if len(source_server.split('/')) == 1:
            source_server = resource_id(subscription=get_subscription_id(cmd.cli_ctx),
                                        resource_group=resource_group_name,
                                        namespace=provider,
                                        type='servers',
                                        name=source_server)
        else:
            raise CLIError('The provided source-server {} is invalid.'.format(source_server))

    source_server_id_parts = parse_resource_id(source_server)
    try:
        source_server_object = client.get(source_server_id_parts['resource_group'], source_server_id_parts['name'])
    except CloudError as e:
        raise CLIError('Unable to get source server: {}.'.format(str(e)))

    parameters = None
    if provider == 'Microsoft.DBForMySQL':
        from azure.mgmt.rdbms import mysql
        parameters = mysql.models.ServerForCreate(
            sku=mysql.models.Sku(name=source_server_object.sku.name),
            properties=mysql.models.ServerPropertiesForReplica(source_server_id=source_server),
            location=source_server_object.location)

    return sdk_no_wait(no_wait, client.create, resource_group_name, server_name, parameters)
def validate_applications(namespace):
    if namespace.resource_group_name:
        if isinstance(namespace.application, list):
            if len(namespace.application) == 1:
                if is_valid_resource_id(namespace.application[0]):
                    raise CLIError("Specify either a full resource id or an application name and resource group.")
            else:
                raise CLIError("Resource group only allowed with a single application name.")
Example #17
0
def validate_subnet(ns):
    from msrestazure.tools import is_valid_resource_id

    # vnet_name is depricated, using for backwards compatability
    if ns.vnet_name and not ns.vnet:
        ns.vnet = ns.vnet_name

    if not is_valid_resource_id(ns.subnet) and ((ns.vnet and not ns.subnet) or (ns.subnet and not ns.vnet)):
        raise CLIError('usage error: --vnet NAME --subnet NAME | --vnet ID --subnet NAME | --subnet ID')
Example #18
0
 def _validate_name_or_id(public_ip):
     # determine if public_ip_address is name or ID
     is_id = is_valid_resource_id(public_ip)
     return public_ip if is_id else resource_id(
         subscription=get_subscription_id(cmd.cli_ctx),
         resource_group=namespace.resource_group_name,
         namespace='Microsoft.Network',
         type='publicIPAddresses',
         name=public_ip)
def validate_express_route_port(cmd, namespace):
    from msrestazure.tools import is_valid_resource_id, resource_id
    if namespace.express_route_port and not is_valid_resource_id(namespace.express_route_port):
        namespace.express_route_port = resource_id(
            subscription=get_subscription_id(cmd.cli_ctx),
            resource_group=namespace.resource_group_name,
            namespace='Microsoft.Network',
            type='expressRoutePorts',
            name=namespace.express_route_port
        )
Example #20
0
def validate_route_filter(cmd, namespace):
    from msrestazure.tools import is_valid_resource_id, resource_id
    if namespace.route_filter:
        if not is_valid_resource_id(namespace.route_filter):
            namespace.route_filter = resource_id(
                subscription=get_subscription_id(cmd.cli_ctx),
                resource_group=namespace.resource_group_name,
                namespace='Microsoft.Network',
                type='routeFilters',
                name=namespace.route_filter)
Example #21
0
def process_ag_http_settings_create_namespace(cmd, namespace):  # pylint: disable=unused-argument
    from msrestazure.tools import is_valid_resource_id
    if namespace.probe and not is_valid_resource_id(namespace.probe):
        namespace.probe = _generate_ag_subproperty_id(
            cmd.cli_ctx, namespace, 'probes', namespace.probe)
    if namespace.auth_certs:
        def _validate_name_or_id(val):
            return val if is_valid_resource_id(val) else _generate_ag_subproperty_id(
                cmd.cli_ctx, namespace, 'authenticationCertificates', val)
        namespace.auth_certs = [_validate_name_or_id(x) for x in namespace.auth_certs]
def validate_virtual_hub(cmd, namespace):
    from msrestazure.tools import is_valid_resource_id, resource_id
    if namespace.virtual_hub and not is_valid_resource_id(namespace.virtual_hub):
        namespace.virtual_hub = resource_id(
            subscription=get_subscription_id(cmd.cli_ctx),
            resource_group=namespace.resource_group_name,
            namespace='Microsoft.Network',
            type='virtualHubs',
            name=namespace.virtual_hub
        )
Example #23
0
 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
Example #24
0
def get_arm_resource_by_id(cli_ctx, arm_id, api_version=None):
    from msrestazure.tools import parse_resource_id, is_valid_resource_id

    if not is_valid_resource_id(arm_id):
        raise CLIError("'{}' is not a valid ID.".format(arm_id))

    client = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES)

    if not api_version:

        parts = parse_resource_id(arm_id)

        # to retrieve the provider, we need to know the namespace
        namespaces = {k: v for k, v in parts.items() if 'namespace' in k}

        # every ARM ID has at least one namespace, so start with that
        namespace = namespaces.pop('namespace')
        namespaces.pop('resource_namespace')
        # find the most specific child namespace (if any) and use that value instead
        highest_child = 0
        for k, v in namespaces.items():
            child_number = int(k.split('_')[2])
            if child_number > highest_child:
                namespace = v
                highest_child = child_number

        # retrieve provider info for the namespace
        provider = client.providers.get(namespace)

        # assemble the resource type key used by the provider list operation.  type1/type2/type3/...
        resource_type_str = ''
        if not highest_child:
            resource_type_str = parts['resource_type']
        else:
            types = {int(k.split('_')[2]): v for k, v in parts.items() if k.startswith('child_type')}
            for k in sorted(types.keys()):
                if k < highest_child:
                    continue
                resource_type_str = '{}{}/'.format(resource_type_str, parts['child_type_{}'.format(k)])
            resource_type_str = resource_type_str.rstrip('/')

        api_version = None
        rt = next((t for t in provider.resource_types if t.resource_type.lower() == resource_type_str.lower()), None)
        if not rt:
            from azure.cli.core.parser import IncorrectUsageError
            raise IncorrectUsageError('Resource type {} not found.'.format(resource_type_str))
        try:
            # if the service specifies, use the default API version
            api_version = rt.default_api_version
        except AttributeError:
            # if the service doesn't specify, use the most recent non-preview API version unless there is only a
            # single API version. API versions are returned by the service in a sorted list
            api_version = next((x for x in rt.api_versions if not x.endswith('preview')), rt.api_versions[0])

    return client.resources.get_by_id(arm_id, api_version)
Example #25
0
def validate_ddos_name_or_id(cmd, namespace):

    if namespace.ddos_protection_plan:
        from msrestazure.tools import is_valid_resource_id, resource_id
        if not is_valid_resource_id(namespace.ddos_protection_plan):
            namespace.ddos_protection_plan = resource_id(
                subscription=get_subscription_id(cmd.cli_ctx),
                resource_group=namespace.resource_group_name,
                namespace='Microsoft.Network', type='ddosProtectionPlans',
                name=namespace.ddos_protection_plan
            )
Example #26
0
def validate_partner_namespace(cmd, namespace):
    from azure.cli.core.commands.client_factory import get_subscription_id
    from msrestazure.tools import is_valid_resource_id, resource_id
    if namespace.partner_namespace:
        if not is_valid_resource_id(namespace.partner_namespace):
            namespace.partner_namespace = resource_id(
                subscription=get_subscription_id(cmd.cli_ctx),
                resource_group=namespace.resource_group_name,
                namespace='Microsoft.ServiceBus',
                type='namespaces',
                name=namespace.partner_namespace)
Example #27
0
def validate_target_listener(cmd, namespace):
    from msrestazure.tools import is_valid_resource_id, resource_id
    if namespace.target_listener and not is_valid_resource_id(namespace.target_listener):
        namespace.target_listener = resource_id(
            subscription=get_subscription_id(cmd.cli_ctx),
            resource_group=namespace.resource_group_name,
            name=namespace.application_gateway_name,
            namespace='Microsoft.Network',
            type='applicationGateways',
            child_type_1='httpListeners',
            child_name_1=namespace.target_listener)
Example #28
0
 def simple_validator(cmd, namespace):
     if namespace.network_security_group:
         # determine if network_security_group is name or ID
         is_id = is_valid_resource_id(namespace.network_security_group)
         if not is_id:
             namespace.network_security_group = resource_id(
                 subscription=get_subscription_id(cmd.cli_ctx),
                 resource_group=namespace.resource_group_name,
                 namespace='Microsoft.Network',
                 type='networkSecurityGroups',
                 name=namespace.network_security_group)
Example #29
0
 def simple_validator(cmd, namespace):
     if namespace.virtual_network:
         # determine if vnet is name or ID
         is_id = is_valid_resource_id(namespace.virtual_network)
         if not is_id:
             namespace.virtual_network = resource_id(
                 subscription=get_subscription_id(cmd.cli_ctx),
                 resource_group=namespace.resource_group_name,
                 namespace='Microsoft.Network',
                 type='virtualNetworks',
                 name=namespace.virtual_network)
Example #30
0
def process_nw_flow_log_set_namespace(cmd, namespace):
    from msrestazure.tools import is_valid_resource_id, resource_id
    if namespace.storage_account and not is_valid_resource_id(namespace.storage_account):
        namespace.storage_account = resource_id(
            subscription=get_subscription_id(cmd.cli_ctx),
            resource_group=namespace.resource_group_name,
            namespace='Microsoft.Storage',
            type='storageAccounts',
            name=namespace.storage_account)

    process_nw_flow_log_show_namespace(cmd, namespace)
Example #31
0
def validate_template_id(cmd, namespace):
    from msrestazure.tools import resource_id, is_valid_resource_id
    from azure.cli.core.commands.client_factory import get_subscription_id
    if not is_valid_resource_id(namespace.arm_template):
        if not namespace.artifact_source_name:
            raise CLIError("--artifact-source-name is required when name is "
                           "provided for --arm-template")

        namespace.arm_template = resource_id(
            subscription=get_subscription_id(cmd.cli_ctx),
            resource_group=namespace.resource_group_name,
            namespace='Microsoft.DevTestLab',
            type='labs',
            name=namespace.lab_name,
            child_type_1='artifactSources',
            child_name_1=namespace.artifact_source_name,
            child_type_2='armTemplates',
            child_name_2=namespace.arm_template)
Example #32
0
def validate_appservice_name_or_id(cmd, namespace):
    from azure.cli.core.commands.client_factory import get_subscription_id
    from msrestazure.tools import is_valid_resource_id, parse_resource_id
    if namespace.appservice_account:
        if not is_valid_resource_id(namespace.appservice_account):
            config_store_name = namespace.name
            if not config_store_name:
                config_store_name = get_store_name_from_connection_string(
                    namespace.connection_string)
            resource_group, _ = resolve_resource_group(cmd, config_store_name)
            namespace.appservice_account = {
                "subscription": get_subscription_id(cmd.cli_ctx),
                "resource_group": resource_group,
                "name": namespace.appservice_account
            }
        else:
            namespace.appservice_account = parse_resource_id(
                namespace.appservice_account)
Example #33
0
def _alert_rule_id(subscription, resource_group, alert):
    """
    Transform alert rule name or ID to alert rule ID
    :param subscription:
    :param resource_group:
    :param alert:
    :return: alert rule ID
    """
    if alert is None:
        return None
    from msrestazure.tools import resource_id, is_valid_resource_id
    if not is_valid_resource_id(alert):
        return resource_id(subscription=subscription,
                           resource_group=resource_group,
                           namespace='microsoft.insights',
                           type='alertrules',
                           name=alert)
    return alert
Example #34
0
 def convert_to_id(rule, key):
     if rule.get(key):
         ids = []
         for p in rule.get(key):
             if isinstance(p, dict):
                 ids.append(
                     "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/applicationSecurityGroups/{2}"
                     .format(self.subscription_id,
                             p.get('resource_group'), p.get('name')))
             elif isinstance(p, str):
                 if is_valid_resource_id(p):
                     ids.append(p)
                 else:
                     ids.append(
                         "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Network/applicationSecurityGroups/{2}"
                         .format(self.subscription_id,
                                 self.resource_group, p))
         rule[key] = ids
Example #35
0
    def _validate_asg_name_or_id(namespace):
        subscription_id = get_subscription_id()
        resource_group = namespace.resource_group_name
        names_or_ids = getattr(namespace, dest)
        ids = []

        if names_or_ids == [""] or not names_or_ids:
            return

        for val in names_or_ids:
            if not is_valid_resource_id(val):
                val = resource_id(subscription=subscription_id,
                                  resource_group=resource_group,
                                  namespace='Microsoft.Network',
                                  type='applicationSecurityGroups',
                                  name=val)
            ids.append(ApplicationSecurityGroup(id=val))
        setattr(namespace, dest, ids)
Example #36
0
def validate_subnet_id(cli_ctx, subnet, vnet_name, resource_group_name):
    from msrestazure.tools import is_valid_resource_id
    subnet_is_id = is_valid_resource_id(subnet)

    if subnet_is_id and not vnet_name:
        return subnet
    if subnet and not subnet_is_id and vnet_name:
        from msrestazure.tools import resource_id
        from azure.cli.core.commands.client_factory import get_subscription_id
        return resource_id(subscription=get_subscription_id(cli_ctx),
                           resource_group=resource_group_name,
                           namespace='Microsoft.Network',
                           type='virtualNetworks',
                           name=vnet_name,
                           child_type_1='subnets',
                           child_name_1=subnet)
    raise ArgumentUsageError(
        'Usage error: --subnet ID | --subnet NAME --vnet-name NAME')
Example #37
0
def validate_network_profile(cmd, ns):
    from azure.cli.core.commands.client_factory import get_subscription_id
    from msrestazure.tools import is_valid_resource_id, resource_id

    if ns.network_profile and ns.ip_address:
        raise CLIError(
            'Can not use "--network-profile" with IP address type "Public".')
    if ns.network_profile and ns.dns_name_label:
        raise CLIError(
            'Can not use "--network-profile" with "--dns-name-label".')
    if ns.network_profile:
        if not is_valid_resource_id(ns.network_profile):
            ns.network_profile = resource_id(
                subscription=get_subscription_id(cmd.cli_ctx),
                resource_group=ns.resource_group_name,
                namespace='Microsoft.Network',
                type='networkProfiles',
                name=ns.network_profile)
Example #38
0
def validate_disk_encryption_set(cmd, namespace):
    if namespace.disk_encryption_set is not None:
        if not is_valid_resource_id(namespace.disk_encryption_set):
            raise InvalidArgumentValueError(
                f"Invalid --disk-encryption-set '{namespace.disk_encryption_set}', has to be a resource ID."
            )

        desid = parse_resource_id(namespace.disk_encryption_set)
        compute_client = get_mgmt_service_client(cmd.cli_ctx,
                                                 ResourceType.MGMT_COMPUTE)
        try:
            compute_client.disk_encryption_sets.get(
                resource_group_name=desid['resource_group'],
                disk_encryption_set_name=desid['name'])
        except CloudError as err:
            raise InvalidArgumentValueError(
                f"Invald --disk-encryption-set, error when getting '{namespace.disk_encryption_set}':"
                f" {str(err)}") from err
Example #39
0
def _generate_lb_id_list_from_names_or_ids(cli_ctx, namespace, prop, child_type):
    from msrestazure.tools import is_valid_resource_id
    raw = getattr(namespace, prop)
    if not raw:
        return
    raw = raw if isinstance(raw, list) else [raw]
    result = []
    for item in raw:
        if is_valid_resource_id(item):
            result.append({'id': item})
        else:
            if not namespace.load_balancer_name:
                raise CLIError('Unable to process {}. Please supply a well-formed ID or '
                               '--lb-name.'.format(item))
            else:
                result.append({'id': _generate_lb_subproperty_id(
                    cli_ctx, namespace, child_type, item)})
    setattr(namespace, prop, result)
Example #40
0
def process_nw_flow_log_show_namespace(cmd, namespace):
    from msrestazure.tools import is_valid_resource_id, resource_id, parse_resource_id

    if not is_valid_resource_id(namespace.nsg):
        namespace.nsg = resource_id(
            subscription=get_subscription_id(cmd.cli_ctx),
            resource_group=namespace.resource_group_name,
            namespace='Microsoft.Network',
            type='networkSecurityGroups',
            name=namespace.nsg)

    network_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_NETWORK).network_security_groups
    id_parts = parse_resource_id(namespace.nsg)
    nsg_name = id_parts['name']
    rg = id_parts['resource_group']
    nsg = network_client.get(rg, nsg_name)
    namespace.location = nsg.location  # pylint: disable=no-member
    get_network_watcher_from_location(remove=True)(cmd, namespace)
Example #41
0
def acr_create(cmd,
               client,
               registry_name,
               resource_group_name,
               sku,
               location=None,
               admin_enabled=False,
               default_action=None,
               tags=None,
               workspace=None,
               identity=None,
               key_encryption_key=None):

    if default_action and sku not in get_premium_sku(cmd):
        raise CLIError(NETWORK_RULE_NOT_SUPPORTED)

    if sku not in get_managed_sku(cmd):
        raise CLIError("Classic SKU is no longer supported. Please select a managed SKU.")

    Registry, Sku, NetworkRuleSet = cmd.get_models('Registry', 'Sku', 'NetworkRuleSet')
    registry = Registry(location=location, sku=Sku(name=sku), admin_user_enabled=admin_enabled, tags=tags)
    if default_action:
        registry.network_rule_set = NetworkRuleSet(default_action=default_action)

    if identity or key_encryption_key:
        _configure_cmk(cmd, registry, resource_group_name, identity, key_encryption_key)

    lro_poller = client.create(resource_group_name, registry_name, registry)

    if workspace:
        from msrestazure.tools import is_valid_resource_id, resource_id
        from azure.cli.core.commands import LongRunningOperation
        from azure.cli.core.commands.client_factory import get_subscription_id
        acr = LongRunningOperation(cmd.cli_ctx)(lro_poller)
        if not is_valid_resource_id(workspace):
            workspace = resource_id(subscription=get_subscription_id(cmd.cli_ctx),
                                    resource_group=resource_group_name,
                                    namespace='microsoft.OperationalInsights',
                                    type='workspaces',
                                    name=workspace)
        _create_diagnostic_settings(cmd.cli_ctx, acr, workspace)
        return acr

    return lro_poller
def flexible_replica_create(cmd,
                            client,
                            resource_group_name,
                            replica_name,
                            server_name,
                            no_wait=False,
                            location=None,
                            sku_name=None,
                            tier=None,
                            **kwargs):
    provider = 'Microsoft.DBforMySQL'

    # set source server id
    if not is_valid_resource_id(server_name):
        if len(server_name.split('/')) == 1:
            server_name = resource_id(subscription=get_subscription_id(
                cmd.cli_ctx),
                                      resource_group=resource_group_name,
                                      namespace=provider,
                                      type='flexibleServers',
                                      name=server_name)
        else:
            raise CLIError('The provided source-server {} is invalid.'.format(
                server_name))

    source_server_id_parts = parse_resource_id(server_name)
    try:
        source_server_object = client.get(
            source_server_id_parts['resource_group'],
            source_server_id_parts['name'])
    except CloudError as e:
        raise CLIError('Unable to get source server: {}.'.format(str(e)))

    location = source_server_object.location
    sku_name = source_server_object.sku.name
    tier = source_server_object.sku.tier

    parameters = mysql_flexibleservers.models.Server(
        sku=mysql_flexibleservers.models.Sku(name=sku_name, tier=tier),
        source_server_id=server_name,
        location=location,
        create_mode="Replica")
    return sdk_no_wait(no_wait, client.begin_create, resource_group_name,
                       replica_name, parameters)
Example #43
0
def sqlvm_aglistener_create(client,
                            cmd,
                            availability_group_listener_name,
                            sql_virtual_machine_group_name,
                            resource_group_name,
                            availability_group_name,
                            ip_address,
                            subnet_resource_id,
                            load_balancer_resource_id,
                            probe_port,
                            sql_virtual_machine_instances,
                            port=1433,
                            public_ip_address_resource_id=None,
                            vnet_name=None):  # pylint: disable=unused-argument
    '''
    Creates an availability group listener
    '''
    # Create the private ip address
    private_ip_object = PrivateIPAddress(
        ip_address=ip_address,
        subnet_resource_id=subnet_resource_id
        if is_valid_resource_id(subnet_resource_id) else None)

    # Create the load balancer configurations
    load_balancer_object = LoadBalancerConfiguration(
        private_ip_address=private_ip_object,
        public_ip_address_resource_id=public_ip_address_resource_id,
        load_balancer_resource_id=load_balancer_resource_id,
        probe_port=probe_port,
        sql_virtual_machine_instances=sql_virtual_machine_instances)

    # Create the availability group listener object
    ag_listener_object = AvailabilityGroupListener(
        availability_group_name=availability_group_name,
        load_balancer_configurations=[load_balancer_object],
        port=port)

    LongRunningOperation(cmd.cli_ctx)(sdk_no_wait(
        False, client.create_or_update, resource_group_name,
        sql_virtual_machine_group_name, availability_group_listener_name,
        ag_listener_object))

    return client.get(resource_group_name, sql_virtual_machine_group_name,
                      availability_group_listener_name)
Example #44
0
    def find_subscriptions_in_vm_with_msi(self, identity_id=None):
        import jwt
        from requests import HTTPError
        from msrestazure.azure_active_directory import MSIAuthentication
        from msrestazure.tools import is_valid_resource_id
        resource = self.cli_ctx.cloud.endpoints.active_directory_resource_id

        if identity_id:
            if is_valid_resource_id(identity_id):
                msi_creds = MSIAuthentication(resource=resource, msi_res_id=identity_id)
                identity_type = MsiAccountTypes.user_assigned_resource_id
            else:
                try:
                    msi_creds = MSIAuthentication(resource=resource, client_id=identity_id)
                    identity_type = MsiAccountTypes.user_assigned_client_id
                except HTTPError as ex:
                    if ex.response.reason == 'Bad Request' and ex.response.status == 400:
                        identity_type = MsiAccountTypes.user_assigned_object_id
                        msi_creds = MSIAuthentication(resource=resource, object_id=identity_id)
                    else:
                        raise
        else:
            identity_type = MsiAccountTypes.system_assigned
            msi_creds = MSIAuthentication(resource=resource)

        token_entry = msi_creds.token
        token = token_entry['access_token']
        logger.info('MSI: token was retrieved. Now trying to initialize local accounts...')
        decode = jwt.decode(token, verify=False, algorithms=['RS256'])
        tenant = decode['tid']

        subscription_finder = SubscriptionFinder(self.cli_ctx, self.auth_ctx_factory, None)
        subscriptions = subscription_finder.find_from_raw_token(tenant, token)
        if not subscriptions:
            raise CLIError('No access was configured for the VM, hence no subscriptions were found')
        base_name = ('{}-{}'.format(identity_type, identity_id) if identity_id else identity_type)
        user = _USER_ASSIGNED_IDENTITY if identity_id else _SYSTEM_ASSIGNED_IDENTITY

        consolidated = self._normalize_properties(user, subscriptions, is_service_principal=True)
        for s in consolidated:
            s[_SUBSCRIPTION_NAME] = base_name
        # key-off subscription name to allow accounts with same id(but under different identities)
        self._set_subscriptions(consolidated, secondary_key_name=_SUBSCRIPTION_NAME)
        return deepcopy(consolidated)
Example #45
0
def _validate_subnet(cmd, namespace):
    from msrestazure.tools import resource_id, is_valid_resource_id
    from azure.cli.core.commands.client_factory import get_subscription_id

    subnet = namespace.subnet
    subnet_is_id = is_valid_resource_id(subnet)
    vnet = namespace.vnet_name

    if (subnet_is_id and not vnet) or (not subnet and not vnet):
        return
    if subnet and not subnet_is_id and vnet:
        namespace.subnet = resource_id(
            subscription=get_subscription_id(cmd.cli_ctx),
            resource_group=namespace.resource_group_name,
            namespace='Microsoft.Network',
            type='virtualNetworks',
            name=vnet,
            child_type_1='subnets',
            child_name_1=subnet)
Example #46
0
def validate_workspace_values(cmd, namespace):
    """Parse managed resource_group which can be either resource group name or id"""
    from msrestazure.tools import is_valid_resource_id, resource_id
    from azure.cli.core.commands.client_factory import get_subscription_id

    random_id = id_generator()
    subscription_id = get_subscription_id(cmd.cli_ctx)
    if not namespace.managed_resource_group:
        namespace.managed_resource_group = resource_id(
            subscription=subscription_id,
            resource_group='databricks-rg-' + namespace.workspace_name + '-' +
            random_id)
    elif not is_valid_resource_id(namespace.managed_resource_group):
        namespace.managed_resource_group = resource_id(
            subscription=subscription_id,
            resource_group=namespace.managed_resource_group)

    # name to resource id for virtual-network
    validate_network_id('custom_virtual_network_id')(cmd, namespace)
def flexible_replica_create(cmd, client, resource_group_name, server_name, source_server, no_wait=False, location=None, sku_name=None, tier=None, **kwargs):
    provider = 'Microsoft.DBforMySQL'

    # set source server id
    if not is_valid_resource_id(source_server):
        if len(source_server.split('/')) == 1:
            source_server = resource_id(subscription=get_subscription_id(cmd.cli_ctx),
                                        resource_group=resource_group_name,
                                        namespace=provider,
                                        type='flexibleServers',
                                        name=source_server)
        else:
            raise CLIError('The provided source-server {} is invalid.'.format(source_server))

    source_server_id_parts = parse_resource_id(source_server)
    try:
        source_server_object = client.get(source_server_id_parts['resource_group'], source_server_id_parts['name'])
    except CloudError as e:
        raise CLIError('Unable to get source server: {}.'.format(str(e)))

    # if location is None:
    #     location = source_server_object.location

    # if sku_name is None:
    #     sku_name = source_server_object.sku.name
    # if tier is None:
    #     tier = source_server_object.sku.tier
    location = source_server_object.location
    sku_name = source_server_object.sku.name
    tier = source_server_object.sku.tier

    # validation
    # sku_info = get_mysql_list_skus_info(cmd, location)
    # mysql_arguments_validator(tier, sku_name, None, None, sku_info)

    from azure.mgmt.rdbms import mysql_flexibleservers

    parameters = mysql_flexibleservers.models.Server(
        sku=mysql_flexibleservers.models.Sku(name=sku_name, tier=tier),
        source_server_id=source_server,
        location=location,
        create_mode="Replica")
    return sdk_no_wait(no_wait, client.create, resource_group_name, server_name, parameters)
Example #48
0
def cli_redis_create_server_link(cmd, client, resource_group_name, name, server_to_link, replication_role):
    redis_client = cf_redis(cmd.cli_ctx)
    from azure.cli.core.commands.client_factory import get_subscription_id
    from msrestazure.tools import is_valid_resource_id, resource_id
    if not is_valid_resource_id(server_to_link):
        server_to_link = resource_id(
            subscription=get_subscription_id(cmd.cli_ctx),
            resource_group=resource_group_name,
            namespace='Microsoft.Cache', type='Redis',
            name=server_to_link
        )

    cache_to_link = get_cache_from_resource_id(redis_client, server_to_link)

    from azure.mgmt.redis.models import RedisLinkedServerCreateParameters
    params = RedisLinkedServerCreateParameters(linked_redis_cache_id=cache_to_link.id,
                                               linked_redis_cache_location=cache_to_link.location,
                                               server_role=replication_role)
    return client.begin_create(resource_group_name, name, cache_to_link.name, params)
Example #49
0
    def validate_action_groups(cmd, namespace):
        action_groups = getattr(namespace, dest, None)

        if not action_groups:
            return

        from msrestazure.tools import is_valid_resource_id, resource_id
        from azure.cli.core.commands.client_factory import get_subscription_id

        subscription = get_subscription_id(cmd.cli_ctx)
        resource_group = namespace.resource_group_name
        for group in action_groups:
            if not is_valid_resource_id(group.action_group_id):
                group.action_group_id = resource_id(
                    subscription=subscription,
                    resource_group=resource_group,
                    namespace='microsoft.insights',
                    type='actionGroups',
                    name=group.action_group_id)
Example #50
0
def get_vnet_validator(cmd, namespace):
    SubResource = cmd.get_models('SubResource')
    subscription_id = get_subscription_id(cmd.cli_ctx)

    resource_group = namespace.resource_group_name
    name_or_id = namespace.virtual_network

    if name_or_id is None:
        return

    if not is_valid_resource_id(name_or_id):
        name_or_id = resource_id(
            subscription=subscription_id,
            resource_group=resource_group,
            namespace='Microsoft.Network', type='virtualNetworks',
            name=name_or_id
        )

    namespace.virtual_network = SubResource(id=name_or_id)
Example #51
0
def validate_lab_vm_list(cmd, namespace):
    """ Validates parameters for lab vm list and updates namespace. """
    from msrestazure.tools import resource_id, is_valid_resource_id
    collection = [namespace.filters, namespace.all, namespace.claimable]
    if _any(collection) and not _single(collection):
        raise CLIError("usage error: [--filters FILTER | [[--all | --claimable][--environment ENVIRONMENT]]")

    collection = [namespace.filters, namespace.environment]
    if _any(collection) and not _single(collection):
        raise CLIError("usage error: [--filters FILTER | [[--all | --claimable][--environment ENVIRONMENT]]")

    if namespace.filters:
        return

    # Retrieve all the vms of the lab
    if namespace.all:
        namespace.filters = None
    # Retrieve all the vms claimable by user
    elif namespace.claimable:
        namespace.filters = 'properties/allowClaim'
    # Default to retrieving users vms only
    else:
        # Find out owner object id
        if not namespace.object_id:
            namespace.filters = "Properties/ownerObjectId eq '{}'".format(_get_owner_object_id(cmd.cli_ctx))

    if namespace.environment:
        if not is_valid_resource_id(namespace.environment):
            from azure.cli.core.commands.client_factory import get_subscription_id
            namespace.environment = resource_id(subscription=get_subscription_id(cmd.cli_ctx),
                                                resource_group=namespace.resource_group_name,
                                                namespace='Microsoft.DevTestLab',
                                                type='labs',
                                                name=namespace.lab_name,
                                                child_type_1='users',
                                                child_name_1=_get_owner_object_id(cmd.cli_ctx),
                                                child_type_2='environments',
                                                child_name_2=namespace.environment)
        if namespace.filters is None:
            namespace.filters = "Properties/environmentId eq '{}'".format(namespace.environment)
        else:
            namespace.filters = "{} and Properties/environmentId eq '{}'".format(namespace.filters,
                                                                                 namespace.environment)
def _validate_resource_name(cmd, resource_id):
    if resource_id is None:
        return

    base_error_msg = "Technical resource argument {0} is invalid.".format(
        resource_id)
    if not is_valid_resource_id(resource_id):
        raise CLIError(base_error_msg)

    parsed_resource = parse_resource_id(resource_id)
    subid = parsed_resource["subscription"]
    if not _is_guid(subid):
        raise CLIError(base_error_msg +
                       "Subscription id {0} is invalid.".format(subid))

    session_subid = get_subscription_id(cmd.cli_ctx)
    if subid != session_subid:
        raise CLIError("{0} {1} does not match with {2}".format(
            base_error_msg, subid, session_subid))
Example #53
0
    def _validate_subnet(cmd, namespace):
        subnet = getattr(namespace, key)

        if not is_valid_resource_id(subnet):
            if not namespace.vnet:
                raise RequiredArgumentMissingError(f"Must specify --vnet if --{key.replace('_', '-')} is not an id.")

            validate_vnet(cmd, namespace)

            subnet = namespace.vnet + '/subnets/' + subnet
            setattr(namespace, key, subnet)

        parts = parse_resource_id(subnet)

        if parts['subscription'] != get_subscription_id(cmd.cli_ctx):
            raise InvalidArgumentValueError(
                f"--{key.replace('_', '-')} subscription '{parts['subscription']}' must equal cluster subscription.")

        if parts['namespace'].lower() != 'microsoft.network':
            raise InvalidArgumentValueError(
                f"--{key.replace('_', '-')} namespace '{parts['namespace']}' must equal Microsoft.Network.")

        if parts['type'].lower() != 'virtualnetworks':
            raise InvalidArgumentValueError(
                f"--{key.replace('_', '-')} type '{parts['type']}' must equal virtualNetworks.")

        if parts['last_child_num'] != 1:
            raise InvalidArgumentValueError(f"--{key.replace('_', '-')} '{subnet}' must have one child.")

        if 'child_namespace_1' in parts:
            raise InvalidArgumentValueError(f"--{key.replace('_', '-')} '{subnet}' must not have child namespace.")

        if parts['child_type_1'].lower() != 'subnets':
            raise InvalidArgumentValueError(f"--{key.replace('_', '-')} child type '{subnet}' must equal subnets.")

        client = get_mgmt_service_client(
            cmd.cli_ctx, ResourceType.MGMT_NETWORK)
        try:
            client.subnets.get(parts['resource_group'],
                               parts['name'], parts['child_name_1'])
        except CloudError as err:
            raise InvalidArgumentValueError(
                f"Invald --{key.replace('_', '-')}, error when getting '{subnet}': {err.message}") from err
Example #54
0
def process_nw_cm_v2_create_namespace(cmd, namespace):

    if namespace.location is None:  # location is None only occurs in creating a V2 connection monitor
        endpoint_source_resource_id = namespace.endpoint_source_resource_id

        from msrestazure.tools import is_valid_resource_id, parse_resource_id
        from azure.mgmt.resource import ResourceManagementClient

        # parse and verify endpoint_source_resource_id
        if endpoint_source_resource_id is None:
            raise CLIError('usage error: '
                           '--location/--endpoint-source-resource-id is required to create a V2 connection monitor')
        if is_valid_resource_id(endpoint_source_resource_id) is False:
            raise CLIError('usage error: "{}" is not a valid resource id'.format(endpoint_source_resource_id))

        resource = parse_resource_id(namespace.endpoint_source_resource_id)
        resource_client = get_mgmt_service_client(cmd.cli_ctx, ResourceManagementClient)
        resource_api_version = _resolve_api_version(resource_client,
                                                    resource['namespace'],
                                                    resource['resource_parent'],
                                                    resource['resource_type'])
        resource = resource_client.resources.get_by_id(namespace.endpoint_source_resource_id, resource_api_version)

        namespace.location = resource.location
        if namespace.location is None:
            raise CLIError("Can not get location from --endpoint-source-resource-id")

    v2_required_parameter_set = ['endpoint_source_name', 'endpoint_dest_name', 'test_config_name']
    for p in v2_required_parameter_set:
        if not hasattr(namespace, p) or getattr(namespace, p) is None:
            raise CLIError(
                'usage error: --{} is required to create a V2 connection monitor'.format(p.replace('_', '-')))
    if namespace.test_config_protocol is None:
        raise CLIError('usage error: --protocol is required to create a test configuration for V2 connection monitor')

    v2_optional_parameter_set = ['workspace_ids']
    if namespace.output_type is not None:
        tmp = [p for p in v2_optional_parameter_set if getattr(namespace, p) is None]
        if v2_optional_parameter_set == tmp:
            raise CLIError('usage error: --output-type is specified but no other resource id provided')

    return get_network_watcher_from_location()(cmd, namespace)
def flexible_server_restore(cmd,
                            client,
                            resource_group_name,
                            server_name,
                            source_server,
                            restore_point_in_time,
                            location=None,
                            no_wait=False):
    provider = 'Microsoft.DBforPostgreSQL'
    if not is_valid_resource_id(source_server):
        if len(source_server.split('/')) == 1:
            source_server_id = resource_id(subscription=get_subscription_id(
                cmd.cli_ctx),
                                           resource_group=resource_group_name,
                                           namespace=provider,
                                           type='flexibleServers',
                                           name=source_server)
        else:
            raise ValueError(
                'The provided source-server {} is invalid.'.format(
                    source_server))
    else:
        source_server_id = source_server

    from azure.mgmt.rdbms import postgresql_flexibleservers
    parameters = postgresql_flexibleservers.models.Server(
        point_in_time_utc=restore_point_in_time,
        source_server_name=
        source_server,  # this should be the source server name, not id
        create_mode="PointInTimeRestore",
        location=location)

    # Retrieve location from same location as source server
    id_parts = parse_resource_id(source_server_id)
    try:
        source_server_object = client.get(id_parts['resource_group'],
                                          id_parts['name'])
        parameters.location = source_server_object.location
    except Exception as e:
        raise ValueError('Unable to get source server: {}.'.format(str(e)))
    return sdk_no_wait(no_wait, client.create, resource_group_name,
                       server_name, parameters)
Example #56
0
def _get_image_reference(image, custom_image):
    """Returns image reference for the given image and custom image.

    :param str image or None: image alias or full spec.
    :param str custom_image or None: resource id of the custom image.
    :raise CLIError: if the image with given alias was not found.
    """
    if custom_image and not image:
        raise CLIError('You need to specify --image argument with information about the custom image')
    if custom_image and not is_valid_resource_id(custom_image):
        raise CLIError('Ill-formed custom image resource id')
    if ':' in image:
        # full image specification is provided
        try:
            publisher, offer, sku, version = image.split(':')
            if not publisher:
                raise CLIError('Image publisher must be provided in --image argument')
            if not offer:
                raise CLIError('Image offer must be provided in --image argument')
            if not sku:
                raise CLIError('Image sku must be provided in --image argument')
            return models.ImageReference(
                publisher=publisher,
                offer=offer,
                sku=sku,
                version=version or None,
                virtual_machine_image_id=custom_image
            )
        except ValueError:
            raise CLIError('--image must have format "publisher:offer:sku:version" or "publisher:offer:sku:"')

    # image alias is used
    reference = None
    for alias, value in SUPPORTED_IMAGE_ALIASES.items():
        if alias.lower() == image.lower():
            reference = value
    if not reference:
        raise CLIError('Unsupported image alias "{0}", supported aliases are {1}'.format(
            image, ', '.join(SUPPORTED_IMAGE_ALIASES.keys())))
    result = copy.deepcopy(reference)
    result.virtual_machine_image_id = custom_image
    return result
Example #57
0
def internal_validate_lock_parameters(namespace, resource_group, resource_provider_namespace,
                                      parent_resource_path, resource_type, resource_name):
    if resource_group is None:
        if resource_name is not None:
            from msrestazure.tools import parse_resource_id, is_valid_resource_id
            if not is_valid_resource_id(resource_name):
                raise CLIError('--resource is not a valid resource ID. '
                               '--resource as a resource name is ignored if --resource-group is not given.')
            # resource-name is an ID, populate namespace
            id_dict = parse_resource_id(resource_name)
            for id_part in ['resource_name', 'resource_type', 'resource_group']:
                setattr(namespace, id_part, id_dict.get(id_part))
            setattr(namespace, 'resource_provider_namespace', id_dict.get('resource_namespace'))
            setattr(namespace, 'parent_resource_path', id_dict.get('resource_parent').strip('/'))

        if resource_type is not None:
            raise CLIError('--resource-type is ignored if --resource-group is not given.')
        if resource_provider_namespace is not None:
            raise CLIError('--namespace is ignored if --resource-group is not given.')
        if parent_resource_path is not None:
            raise CLIError('--parent is ignored if --resource-group is not given.')
        return

    if resource_name is None:
        if resource_type is not None:
            raise CLIError('--resource-type is ignored if --resource is not given.')
        if resource_provider_namespace is not None:
            raise CLIError('--namespace is ignored if --resource is not given.')
        if parent_resource_path is not None:
            raise CLIError('--parent is ignored if --resource is not given.')
        return

    if not resource_type:
        raise CLIError('--resource-type is required if the name, --resource, is present')

    parts = resource_type.split('/')
    if resource_provider_namespace is None:
        if len(parts) == 1:
            raise CLIError('A resource namespace is required if the name, --resource, is present.'
                           'Expected <namespace>/<type> or --namespace=<namespace>')
    elif len(parts) != 1:
        raise CLIError('Resource namespace specified in both --resource-type and --namespace')
def flexible_server_restore(cmd,
                            client,
                            resource_group_name,
                            server_name,
                            source_server,
                            restore_point_in_time,
                            location=None,
                            no_wait=False):
    provider = 'Microsoft.DBforMySQL'
    validate_server_name(
        cf_mysql_check_resource_availability(cmd.cli_ctx, '_'), server_name,
        'Microsoft.DBforMySQL/flexibleServers')

    if not is_valid_resource_id(source_server):
        if len(source_server.split('/')) == 1:
            source_server = resource_id(subscription=get_subscription_id(
                cmd.cli_ctx),
                                        resource_group=resource_group_name,
                                        namespace=provider,
                                        type='flexibleServers',
                                        name=source_server)
        else:
            raise ValueError(
                'The provided source-server {} is invalid.'.format(
                    source_server))

    parameters = mysql_flexibleservers.models.Server(
        source_server_id=source_server,
        restore_point_in_time=restore_point_in_time,
        location=location,
        create_mode="PointInTimeRestore")

    # Retrieve location from same location as source server
    id_parts = parse_resource_id(source_server)
    try:
        source_server_object = client.get(id_parts['resource_group'],
                                          id_parts['name'])
        parameters.location = source_server_object.location
    except Exception as e:
        raise ValueError('Unable to get source server: {}.'.format(str(e)))
    return sdk_no_wait(no_wait, client.begin_create, resource_group_name,
                       server_name, parameters)
Example #59
0
def get_key_for_storage_account(cmd, storage_account):  # pylint: disable=unused-argument
    from ._client_factory import cf_storage
    from msrestazure.tools import parse_resource_id, is_valid_resource_id
    from knack.util import CLIError

    storage_account_key = None
    if is_valid_resource_id(storage_account):
        parsed_storage_account = parse_resource_id(storage_account)
        resource_group_name = parsed_storage_account['resource_group']
        storage_account_name = parsed_storage_account['resource_name']

        storage_client = cf_storage(cmd.cli_ctx)
        keys = storage_client.storage_accounts.list_keys(
            resource_group_name, storage_account_name)
        storage_account_key = keys.keys[0].value  # pylint: disable=no-member
    elif storage_account:
        raise CLIError(
            'Failed to get access key for storage account: {}'.format(
                storage_account))
    return storage_account_key
Example #60
0
def _verify_subnet(client, subnet, nfs_name, nfs_resource_group):
    if not subnet:
        return
    if not is_valid_resource_id(subnet):
        raise CLIError('Ill-formed subnet resource id')

    # check there are no conflicts between provided subnet and mounted nfs
    if not nfs_name:
        return
    nfs = None  # type: models.FileServer
    try:
        nfs = client.file_servers.get(nfs_name, nfs_resource_group)
    except CloudError as e:
        if e.status_code != 404:
            raise
    if not nfs:
        # CLI will return the error during nfs validation
        return
    if nfs.subnet.id != subnet:
        raise CLIError('Cluster and mounted NFS must be in the same subnet.')