Пример #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
Пример #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)
Пример #3
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
Пример #4
0
def _validate_name_or_id(
        resource_group_name, property_value, property_type, parent_value, parent_type):
    from azure.cli.core.commands.client_factory import get_subscription_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(),
            child_name=property_value,
            child_type=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())
        value_supplied_was_id = False
    return (resource_id_parts, value_supplied_was_id)
Пример #5
0
    def handle_folding(namespace):
        base_name_val = getattr(namespace, base_name)
        type_field_val = getattr(namespace, type_field)
        parent_name_val = getattr(namespace, parent_name) if parent_name else None

        if base_name_val is None or type_field_val is not None:
            # Either no name was specified, or the user specified the type of resource
            # (i.e. new/existing/none)
            pass
        elif base_name_val in ('', '""', "''"):
            # An empty name specified - that means that we are neither referencing an existing
            # field, or the name is set to an empty string.  We check for all types of quotes
            # so scripts can run cross-platform.
            if not none_flag_value:
                raise CLIError('Field {} cannot be none.'.format(make_camel_case(base_name)))
            setattr(namespace, type_field, none_flag_value)
            setattr(namespace, base_name, None)
        else:
            from azure.cli.core.commands.client_factory import get_subscription_id
            has_parent = parent_name is not None and parent_type is not None
            if is_valid_resource_id(base_name_val):
                resource_id_parts = parse_resource_id(base_name_val)
            elif has_parent:
                if not parent_name_val and base_required:
                    raise CLIError("Must specify '{}' when specifying '{}' name.".format(
                        parent_option_flag or parent_name, base_name))
                resource_id_parts = dict(
                    name=parent_name_val,
                    resource_group=namespace.resource_group_name,
                    namespace=parent_type.split('/')[0],
                    type=parent_type.split('/')[1],
                    subscription=get_subscription_id(),
                    child_name=base_name_val,
                    child_type=resource_type)
            else:
                resource_id_parts = dict(
                    name=base_name_val,
                    resource_group=namespace.resource_group_name,
                    namespace=resource_type.split('/')[0],
                    type=resource_type.split('/')[1],
                    subscription=get_subscription_id())

            if resource_exists(**resource_id_parts):
                setattr(namespace, type_field, existing_id_flag_value)
                setattr(namespace, base_name, resource_id(**resource_id_parts))
            elif is_valid_resource_id(base_name_val):
                raise CLIError('ID {} does not exist. Please specify '
                               'a name to create a new resource.'.format(
                                   resource_id(**resource_id_parts)))
            elif not new_flag_value:
                raise CLIError('Referenced resource {} does not exist. Please create the required '
                               'resource and try again.'.format(resource_id(**resource_id_parts)))
            else:
                setattr(namespace, type_field, new_flag_value)
Пример #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
Пример #7
0
def validate_diagnostic_settings(namespace):
    from azure.cli.core.commands.client_factory import get_subscription_id
    resource_group_error = "--resource-group is required when name is provided for "\
                           "storage account or workspace or service bus namespace and rule. "

    if namespace.namespace or namespace.rule_name:
        if namespace.namespace is None:
            raise CLIError(resource_group_error)
        if namespace.rule_name is None:
            raise CLIError(resource_group_error)
        if namespace.resource_group is None:
            raise CLIError(resource_group_error)

        if not is_valid_resource_id(namespace.namespace):
            namespace.service_bus_rule_id = resource_id(subscription=get_subscription_id(),
                                                        resource_group=namespace.resource_group,
                                                        namespace='microsoft.ServiceBus',
                                                        type='namespaces',
                                                        name=namespace.namespace,
                                                        child_type='AuthorizationRules',
                                                        child_name=namespace.rule_name)
        else:
            resource_dict = parse_resource_id(namespace.namespace)
            namespace.service_bus_rule_id = resource_id(subscription=resource_dict['subscription'],
                                                        resource_group=resource_dict['resource_group'],
                                                        namespace=resource_dict['namespace'],
                                                        type=resource_dict['type'],
                                                        name=resource_dict['name'],
                                                        child_type='AuthorizationRules',
                                                        child_name=namespace.rule_name)

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

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

    _validate_tags(namespace)
Пример #8
0
def _validate_vm_create_nics(namespace):
    nics_value = namespace.nics
    nics = []

    if not nics_value:
        namespace.nic_type = 'new'
        return

    if not isinstance(nics_value, list):
        nics_value = [nics_value]

    for n in nics_value:
        nics.append({
            'id': n if '/' in n else resource_id(name=n,
                                                 resource_group=namespace.resource_group_name,
                                                 namespace='Microsoft.Network',
                                                 type='networkInterfaces',
                                                 subscription=get_subscription_id()),
            'properties': {
                'primary': nics_value[0] == n
            }
        })

    namespace.nics = nics
    namespace.nic_type = 'existing'
    namespace.public_ip_type = None
Пример #9
0
def create(cmd, client, resource_group_name, activity_log_alert_name, scopes=None, condition=None,
           action_groups=frozenset(), tags=None, disable=False, description=None, webhook_properties=None):
    from msrestazure.tools import resource_id
    from azure.mgmt.monitor.models import (ActivityLogAlertResource, ActivityLogAlertAllOfCondition,
                                           ActivityLogAlertLeafCondition, ActivityLogAlertActionList)
    from azure.mgmt.monitor.models import ActivityLogAlertActionGroup as ActionGroup
    from azure.cli.core.commands.client_factory import get_subscription_id
    from knack.util import CLIError

    if not scopes:
        scopes = [resource_id(subscription=get_subscription_id(cmd.cli_ctx), resource_group=resource_group_name)]

    if _get_alert_settings(client, resource_group_name, activity_log_alert_name, throw_if_missing=False):
        raise CLIError('The activity log alert {} already exists in resource group {}.'.format(activity_log_alert_name,
                                                                                               resource_group_name))

    # Add alert conditions
    condition = condition or ActivityLogAlertAllOfCondition(
        all_of=[ActivityLogAlertLeafCondition(field='category', equals='ServiceHealth')])

    # Add action groups
    action_group_rids = _normalize_names(cmd.cli_ctx, action_groups, resource_group_name, 'microsoft.insights',
                                         'actionGroups')
    action_groups = [ActionGroup(action_group_id=i, webhook_properties=webhook_properties) for i in action_group_rids]
    alert_actions = ActivityLogAlertActionList(action_groups=action_groups)

    settings = ActivityLogAlertResource(location='global', scopes=scopes, condition=condition,
                                        actions=alert_actions, enabled=not disable, description=description, tags=tags)

    return client.create_or_update(resource_group_name=resource_group_name,
                                   activity_log_alert_name=activity_log_alert_name, activity_log_alert=settings)
Пример #10
0
def _handle_vm_nics(namespace):
    from azure.cli.core.commands.client_factory import get_subscription_id
    nics_value = namespace.network_interface_ids
    nics = []

    if not nics_value:
        namespace.network_interface_type = 'new'
        return

    namespace.network_interface_type = 'existing'

    if not isinstance(nics_value, list):
        nics_value = [nics_value]

    for n in nics_value:
        nics.append({
            'id': n if '/' in n else resource_id(name=n,
                                                 resource_group=namespace.resource_group_name,
                                                 namespace='Microsoft.Network',
                                                 type='networkInterfaces',
                                                 subscription=get_subscription_id()),
            'properties': {
                'primary': nics_value[0] == n
            }
        })

    namespace.network_interface_ids = nics
    namespace.network_interface_type = 'existing'

    namespace.public_ip_address_type = 'none'
Пример #11
0
def validate_nsg_name(namespace):
    from azure.cli.core.commands.client_factory import get_subscription_id
    vm_id = resource_id(name=namespace.vm_name, resource_group=namespace.resource_group_name,
                        namespace='Microsoft.Compute', type='virtualMachines',
                        subscription=get_subscription_id())
    namespace.network_security_group_name = namespace.network_security_group_name \
        or '{}_NSG_{}'.format(namespace.vm_name, hash_string(vm_id, length=8))
Пример #12
0
def _validate_vm_create_nics(namespace):
    from azure.cli.core.commands.client_factory import get_subscription_id
    nics_value = namespace.nics
    nics = []

    if not nics_value:
        namespace.nic_type = 'new'
        logger.debug('new NIC will be created')
        return

    if not isinstance(nics_value, list):
        nics_value = [nics_value]

    for n in nics_value:
        nics.append({
            'id': n if '/' in n else resource_id(name=n,
                                                 resource_group=namespace.resource_group_name,
                                                 namespace='Microsoft.Network',
                                                 type='networkInterfaces',
                                                 subscription=get_subscription_id()),
            'properties': {
                'primary': nics_value[0] == n
            }
        })

    namespace.nics = nics
    namespace.nic_type = 'existing'
    namespace.public_ip_type = None
    logger.debug('existing NIC(s) will be used')
Пример #13
0
def validate_subnet_name_or_id(namespace):
    """ Validates a subnet ID or, if a name is provided, formats it as an ID. """
    if namespace.virtual_network_name is None and namespace.subnet is None:
        return
    if namespace.subnet == '':
        return
    # error if vnet-name is provided without subnet
    if namespace.virtual_network_name and not namespace.subnet:
        raise CLIError('You must specify --subnet name when using --vnet-name.')

    # 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 argparse.ArgumentError(None, 'Please omit --vnet-name when specifying a subnet ID')
    elif not is_id and not namespace.virtual_network_name:
        raise argparse.ArgumentError(None,
                                     'Please specify --vnet-name when specifying a subnet name')
    if not is_id:
        namespace.subnet = resource_id(
            subscription=get_subscription_id(),
            resource_group=namespace.resource_group_name,
            namespace='Microsoft.Network',
            type='virtualNetworks',
            name=namespace.virtual_network_name,
            child_type='subnets',
            child_name=namespace.subnet)
Пример #14
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)
Пример #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)
Пример #16
0
def _db_create_special(
        client,
        source_db,
        dest_db,
        kwargs):

    # Determine server location
    kwargs['location'] = get_server_location(
        server_name=dest_db.server_name,
        resource_group_name=dest_db.resource_group_name)

    # Set create mode properties
    subscription_id = get_subscription_id()
    kwargs['source_database_id'] = (
        '/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Sql/servers/{}/databases/{}'
        .format(quote(subscription_id),
                quote(source_db.resource_group_name),
                quote(source_db.server_name),
                quote(source_db.database_name)))

    # Create
    return client.create_or_update(
        server_name=dest_db.server_name,
        resource_group_name=dest_db.resource_group_name,
        database_name=dest_db.database_name,
        parameters=kwargs)
Пример #17
0
    def _validator(namespace):
        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}-namespace NAMESPACE [--{0}-parent PARENT] '
                               '[--{0}-type TYPE]'.format(dest))
        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(), rg, res_ns, parent + '/' if parent else '',
                            res_type, name_or_id))

        del namespace.namespace
        del namespace.parent
        del namespace.resource_type
Пример #18
0
def _execute_remediation_operation(
        cmd,
        client,
        operation_name,
        management_group_name=None,
        resource_group_name=None,
        resource=None,
        namespace=None,
        resource_type_parent=None,
        resource_type=None,
        remediation_name=None):

    subscription_id = get_subscription_id(cmd.cli_ctx)
    scope = _build_remediation_scope(
        management_group_name,
        subscription_id,
        resource_group_name,
        resource,
        resource_type_parent,
        resource_type,
        namespace)

    operation = getattr(client, operation_name)
    if remediation_name is None:
        return operation(resource_id=_remove_leading_and_trailing_slash(scope))
    return operation(resource_id=_remove_leading_and_trailing_slash(scope), remediation_name=remediation_name)
Пример #19
0
def _get_resource_id(val, resource_group, resource_type, resource_namespace):
    from azure.cli.core.commands.client_factory import get_subscription_id
    if is_valid_resource_id(val):
        return val

    return resource_id(name=val, resource_group=resource_group, namespace=resource_namespace, type=resource_type,
                       subscription=get_subscription_id())
Пример #20
0
def get_vnet_validator(dest):

    SubResource = get_sdk(ResourceType.MGMT_NETWORK, 'SubResource', mod='models')
    subscription_id = get_subscription_id()

    def _validate_vnet_name_or_id(namespace):
        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='virtualNetworks',
                    name=val
                )
            ids.append(SubResource(id=val))
        setattr(namespace, dest, ids)

    return _validate_vnet_name_or_id
Пример #21
0
def _get_scope(
        resource_group_name,
        provider_namespace,
        resource_type,
        resource_name):
    subscription_id = get_subscription_id()

    if provider_namespace == RESOURCES_NAMESPACE:
        if resource_group_name:
            scope = (
                '/subscriptions/{}/resourceGroups/{}'
                .format(quote(subscription_id),
                        quote(resource_group_name)))
        else:
            scope = (
                '/subscriptions/{}'
                .format(quote(subscription_id)))
    else:
        scope = (
            '/subscriptions/{}/resourceGroups/{}/providers/{}/{}/{}'
            .format(quote(subscription_id),
                    quote(resource_group_name),
                    quote(provider_namespace),
                    quote(resource_type),
                    quote(resource_name)))

    return scope
Пример #22
0
def _get_arm_resource_info(resource_group_name):
    if resource_group_name:
        resource_type = RESOURCE_TYPE_RESOURCE_GROUPS
        resource_name = resource_group_name
    else:
        resource_type = RESOURCE_TYPE_SUBSCRIPTIONS
        resource_name = get_subscription_id()

    return resource_type, resource_name
Пример #23
0
def _generate_ag_subproperty_id(namespace, child_type, child_name, subscription=None):
    return resource_id(
        subscription=subscription or get_subscription_id(),
        resource_group=namespace.resource_group_name,
        namespace='Microsoft.Network',
        type='applicationGateways',
        name=namespace.application_gateway_name,
        child_type=child_type,
        child_name=child_name)
def _validate_artifacts(namespace):
    if namespace.artifacts:
        from azure.cli.core.commands.client_factory import get_subscription_id
        lab_resource_id = resource_id(subscription=get_subscription_id(),
                                      resource_group=namespace.resource_group,
                                      namespace='Microsoft.DevTestLab',
                                      type='labs',
                                      name=namespace.lab_name)
        namespace.artifacts = _update_artifacts(namespace.artifacts, lab_resource_id)
Пример #25
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)
Пример #26
0
def _generate_lb_subproperty_id(namespace, child_type, child_name, subscription=None):
    return resource_id(
        subscription=subscription or get_subscription_id(),
        resource_group=namespace.resource_group_name,
        namespace='Microsoft.Network',
        type='loadBalancers',
        name=namespace.load_balancer_name,
        child_type=child_type,
        child_name=child_name)
Пример #27
0
def validate_route_filter(namespace):
    if namespace.route_filter:
        if not is_valid_resource_id(namespace.route_filter):
            namespace.route_filter = resource_id(
                subscription=get_subscription_id(),
                resource_group=namespace.resource_group_name,
                namespace='Microsoft.Network',
                type='routeFilters',
                name=namespace.route_filter)
Пример #28
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)
Пример #29
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
Пример #30
0
def _generate_ag_subproperty_id(cli_ctx, namespace, child_type, child_name, subscription=None):
    from msrestazure.tools import resource_id
    return resource_id(
        subscription=subscription or get_subscription_id(cli_ctx),
        resource_group=namespace.resource_group_name,
        namespace='Microsoft.Network',
        type='applicationGateways',
        name=namespace.application_gateway_name,
        child_type_1=child_type,
        child_name_1=child_name)
Пример #31
0
    def _validate_vnet_name_or_id(cmd, namespace):
        SubResource = cmd.get_models('SubResource')
        subscription_id = get_subscription_id(cmd.cli_ctx)

        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='virtualNetworks',
                                  name=val)
            ids.append(SubResource(id=val))
        setattr(namespace, dest, ids)
Пример #32
0
    def create_or_update(cls, cmd, resource_group_name, container_app_name, auth_config_name, auth_config_envelope, no_wait=False):
        management_hostname = cmd.cli_ctx.cloud.endpoints.resource_manager
        api_version = STABLE_API_VERSION
        sub_id = get_subscription_id(cmd.cli_ctx)
        request_url = f"{management_hostname}subscriptions/{sub_id}/resourceGroups/{resource_group_name}/providers/Microsoft.App/containerApps/{container_app_name}/authConfigs/{auth_config_name}?api-version={api_version}"

        if "properties" not in auth_config_envelope:  # sdk does this for us
            temp_env = auth_config_envelope
            auth_config_envelope = {}
            auth_config_envelope["properties"] = temp_env

        r = send_raw_request(cmd.cli_ctx, "PUT", request_url, body=json.dumps(auth_config_envelope))

        if no_wait:
            return r.json()
        elif r.status_code == 201:
            request_url = f"{management_hostname}subscriptions/{sub_id}/resourceGroups/{resource_group_name}/providers/Microsoft.App/containerApps/{container_app_name}/authConfigs/{auth_config_name}?api-version={api_version}"
            return poll(cmd, request_url, "waiting")

        return r.json()
Пример #33
0
    def delete(cls, cmd, resource_group_name, container_app_name, auth_config_name, no_wait=False):
        management_hostname = cmd.cli_ctx.cloud.endpoints.resource_manager
        api_version = STABLE_API_VERSION
        sub_id = get_subscription_id(cmd.cli_ctx)
        request_url = f"{management_hostname}subscriptions/{sub_id}/resourceGroups/{resource_group_name}/providers/Microsoft.App/containerApps/{container_app_name}/authConfigs/{auth_config_name}?api-version={api_version}"

        r = send_raw_request(cmd.cli_ctx, "DELETE", request_url)

        if no_wait:
            return  # API doesn't return JSON (it returns no content)
        elif r.status_code in [200, 201, 202, 204]:
            request_url = f"{management_hostname}subscriptions/{sub_id}/resourceGroups/{resource_group_name}/providers/Microsoft.App/containerApps/{container_app_name}/authConfigs/{auth_config_name}?api-version={api_version}"
            if r.status_code == 200:  # 200 successful delete, 204 means storage not found
                from azure.cli.core.azclierror import ResourceNotFoundError
                try:
                    poll(cmd, request_url, "scheduledfordelete")
                except ResourceNotFoundError:
                    pass
                logger.warning('Containerapp AuthConfig successfully deleted')
        return
Пример #34
0
    def list_certificates(cls, cmd, resource_group_name, name, formatter=lambda x: x):
        certs_list = []

        management_hostname = cmd.cli_ctx.cloud.endpoints.resource_manager
        api_version = STABLE_API_VERSION
        sub_id = get_subscription_id(cmd.cli_ctx)
        url_fmt = "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.App/managedEnvironments/{}/certificates?api-version={}"
        request_url = url_fmt.format(
            management_hostname.strip('/'),
            sub_id,
            resource_group_name,
            name,
            api_version)

        r = send_raw_request(cmd.cli_ctx, "GET", request_url, body=None)
        j = r.json()
        for cert in j["value"]:
            formatted = formatter(cert)
            certs_list.append(formatted)
        return certs_list
Пример #35
0
    def __init__(self, cmd, resource_group_name=None, workspace_name=None, location=None):
        from azure.cli.core.commands.client_factory import get_subscription_id

        # Hierarchically selects the value for the given key.
        # First tries the value provided as argument, as that represents the value from the command line
        # then it checks if the key exists in the 'quantum' section in config, and uses that if available.
        # finally, it checks in the 'global' section in the config.
        def select_value(key, value):
            if value is not None:
                return value
            value = cmd.cli_ctx.config.get('quantum', key, None)
            if value is not None:
                return value
            value = cmd.cli_ctx.config.get(cmd.cli_ctx.config.defaults_section_name, key, None)
            return value

        self.subscription = get_subscription_id(cmd.cli_ctx)
        self.resource_group = select_value('group', resource_group_name)
        self.name = select_value('workspace', workspace_name)
        self.location = select_value('location', location)
Пример #36
0
def validate_ip_groups(cmd, namespace):
    from msrestazure.tools import is_valid_resource_id, resource_id

    def _validate_name_or_id(ip_group, subscription):
        # determine if public_ip_address is name or ID
        is_id = is_valid_resource_id(ip_group)
        return ip_group if is_id else resource_id(
            subscription=subscription,
            resource_group=namespace.resource_group_name,
            namespace='Microsoft.Network',
            type='ipGroups',
            name=ip_group)

    subscription = get_subscription_id(cmd.cli_ctx)
    if hasattr(namespace, 'destination_ip_groups') and namespace.destination_ip_groups is not None:
        for i, ip_group in enumerate(namespace.destination_ip_groups):
            namespace.destination_ip_groups[i] = _validate_name_or_id(ip_group, subscription)
    if hasattr(namespace, 'source_ip_groups') and namespace.source_ip_groups is not None:
        for i, ip_group in enumerate(namespace.source_ip_groups):
            namespace.source_ip_groups[i] = _validate_name_or_id(ip_group, subscription)
Пример #37
0
def process_nw_flow_log_show_namespace(namespace):

    from azure.cli.core.commands.arm import parse_resource_id

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

    network_client = get_mgmt_service_client(
        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)(namespace)
Пример #38
0
def _validate_vm_create_availability_set(namespace):
    from azure.cli.core.commands.client_factory import get_subscription_id
    if namespace.availability_set:
        as_id = parse_resource_id(namespace.availability_set)
        name = as_id['name']
        rg = as_id.get('resource_group', namespace.resource_group_name)

        if not check_existence(name, rg, 'Microsoft.Compute',
                               'availabilitySets'):
            raise CLIError(
                "Availability set '{}' does not exist.".format(name))

        namespace.availability_set = resource_id(
            subscription=get_subscription_id(),
            resource_group=rg,
            namespace='Microsoft.Compute',
            type='availabilitySets',
            name=name)
        logger.debug("adding to specified availability set '%s'",
                     namespace.availability_set)
Пример #39
0
def migration_create_func(cmd,
                          client,
                          resource_group_name,
                          server_name,
                          properties,
                          migration_id=None):

    subscription_id = get_subscription_id(cmd.cli_ctx)

    if migration_id is None:
        # Convert a UUID to a string of hex digits in standard form
        migration_id = str(uuid.uuid4())

    r = send_raw_request(
        cmd.cli_ctx, "put",
        "https://management.azure.com/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{}/migrations/{}?api-version=2020-02-14-privatepreview"
        .format(subscription_id, resource_group_name, server_name,
                migration_id), None, None, properties)

    return r.json()
Пример #40
0
def _db_create_special(client, source_db, dest_db, kwargs):

    # Determine server location
    kwargs['location'] = get_server_location(
        server_name=dest_db.server_name,
        resource_group_name=dest_db.resource_group_name)

    # Set create mode properties
    subscription_id = get_subscription_id()
    kwargs['source_database_id'] = (
        '/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Sql/servers/{}/databases/{}'
        .format(quote(subscription_id), quote(source_db.resource_group_name),
                quote(source_db.server_name), quote(source_db.database_name)))

    # Create
    return client.create_or_update(
        server_name=dest_db.server_name,
        resource_group_name=dest_db.resource_group_name,
        database_name=dest_db.database_name,
        parameters=kwargs)
Пример #41
0
def get_resource_id(
    cmd,
    resource_group_name: str,
    provider_name_space: str,
    resource_type: str,
    resource: str,
):
    """
    Gets the resource id for the resource if name is given.
    """

    if resource is None or is_valid_resource_id(resource):
        return resource
    return resource_id(
        subscription=get_subscription_id(cmd.cli_ctx),
        resource_group=resource_group_name,
        namespace=provider_name_space,
        type=resource_type,
        name=resource,
    )
Пример #42
0
def validate_subnet(cmd, namespace):

    subnet = namespace.virtual_network_subnet_id
    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):
        pass
    elif subnet and not subnet_is_id and vnet:
        namespace.virtual_network_subnet_id = 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)
    else:
        raise CLIError('incorrect usage: [--subnet ID | --subnet NAME --vnet-name NAME]')
    delattr(namespace, 'vnet_name')
Пример #43
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
                )
Пример #44
0
def ml_endpoint_get_deployment_logs(cmd,
                                    resource_group_name,
                                    workspace_name,
                                    name,
                                    deployment,
                                    tail,
                                    type=ONLINE_ENDPOINT_TYPE,
                                    container=None):
    subscription_id = get_subscription_id(cmd.cli_ctx)
    ml_client = MLClient(
        subscription_id=subscription_id,
        resource_group_name=resource_group_name,
        default_workspace_name=workspace_name,
        credential=AzureCliCredential(),
    )
    return ml_client.endpoints.get_deployment_logs(type=type,
                                                   endpoint_name=name,
                                                   deployment_name=deployment,
                                                   tail=tail,
                                                   container_type=container)
Пример #45
0
    def test_webapp_storagetable_e2e(self):
        self.kwargs.update({
            'name': 'testconn1',
            'subscription': get_subscription_id(self.cli_ctx),
            'source_resource_group': 'servicelinker-test-linux-group',
            'target_resource_group': 'servicelinker-test-linux-group',
            'site': 'servicelinker-storagetable-app',
            'account': 'servicelinkerteststorage'
        })

        # prepare params
        name = 'testconn'
        
        target_id = TARGET_RESOURCES.get(RESOURCE.StorageTable).format(**self.kwargs)

        # create connection
        self.cmd('webapp connection create storage-table --connection {name} -g {source_resource_group} -n {site} '
                 '--tg {target_resource_group} --account {account} --secret --client-type python')

        # list connection
        connections = self.cmd(
            'webapp connection list -g {source_resource_group} -n {site}',
            checks = [
                self.check('length(@)', 1),
                self.check('[0].authInfo.authType', 'secret'),
                self.check('[0].clientType', 'python')
            ]
        ).get_output_in_json()
        connection_id = connections[0].get('id')

        # list configuration
        self.cmd('webapp connection list-configuration --connection {name} -g {source_resource_group} -n {site}')

        # validate connection
        self.cmd('webapp connection validate --connection {name} -g {source_resource_group} -n {site}')

        # show connection
        self.cmd('webapp connection show --connection {name} -g {source_resource_group} -n {site}')

        # delete connection
        self.cmd('webapp connection delete --id {} --yes'.format(connection_id))
Пример #46
0
    def test_webapp_appconfig_e2e(self):
        self.kwargs.update({
            'name': 'testconn1',
            'subscription': get_subscription_id(self.cli_ctx),
            'source_resource_group': 'servicelinker-test-linux-group',
            'target_resource_group': 'servicelinker-test-linux-group',
            'site': 'servicelinker-config-app',
            'config_store': 'servicelinker-app-configuration'
        })

        # prepare params
        name = 'testconn'
        
        target_id = TARGET_RESOURCES.get(RESOURCE.AppConfig).format(**self.kwargs)

        # create connection
        self.cmd('webapp connection create appconfig --connection {name} -g {source_resource_group} -n {site} '
                 '--tg {target_resource_group} --app-config {config_store} --system-identity --client-type python')
        
        # list connection
        connections = self.cmd(
            'webapp connection list -g {source_resource_group} -n {site}',
            checks = [
                self.check('length(@)', 1),
                self.check('[0].authInfo.authType', 'systemAssignedIdentity'),
                self.check('[0].clientType', 'python')
            ]
        ).get_output_in_json()
        connection_id = connections[0].get('id')

        # list configuration
        self.cmd('webapp connection list-configuration --connection {name} -g {source_resource_group} -n {site}')

        # validate connection
        self.cmd('webapp connection validate --connection {name} -g {source_resource_group} -n {site}')

        # show connection
        self.cmd('webapp connection show --connection {name} -g {source_resource_group} -n {site}')

        # delete connection
        self.cmd('webapp connection delete --id {} --yes'.format(connection_id))
    def test_webapp_confluentkafka_e2e(self):
        self.kwargs.update({
            'subscription': get_subscription_id(self.cli_ctx),
            'source_resource_group': 'servicelinker-test-linux-group',
            'target_resource_group': 'servicelinker-test-linux-group',
            'site': 'servicelinker-kafka-app2',
        })

        # prepare params
        name = 'testconn'
        source_id = SOURCE_RESOURCES.get(RESOURCE.WebApp).format(**self.kwargs)

        # create connection
        self.cmd(
            'webapp connection create confluent-cloud --connection {} --source-id {} '
            '--bootstrap-server xxx.eastus.azure.confluent.cloud:9092 --kafka-key Name --kafka-secret Secret '
            '--schema-registry https://xxx.eastus.azure.confluent.cloud --schema-key Name --schema-secret Secret '
            '--client-type python'.format(name, source_id))

        # list connection
        connections = self.cmd(
            'webapp connection list --source-id {}'.format(source_id),
            checks=[
                self.check('length(@)', 2),
                self.check('[0].clientType', 'python')
            ]).get_output_in_json()
        connection_id = connections[0].get('id')

        # list configuration
        self.cmd('webapp connection list-configuration --id {}'.format(
            connection_id))

        # validate connection
        self.cmd('webapp connection validate --id {}'.format(connection_id))

        # show connection
        self.cmd('webapp connection show --id {}'.format(connection_id))

        # delete connection
        self.cmd(
            'webapp connection delete --id {} --yes'.format(connection_id))
Пример #48
0
def restore_webapp_snapshot(cmd,
                            resource_group,
                            name,
                            time,
                            slot=None,
                            restore_config=False,
                            source_resource_group=None,
                            source_name=None,
                            source_slot=None):
    client = web_client_factory(cmd.cli_ctx)

    if all([source_resource_group, source_name]):
        sub_id = get_subscription_id(cmd.cli_ctx)
        target_id = "/subscriptions/" + sub_id + "/resourceGroups/" + resource_group + "/providers/Microsoft.Web/sites/" + name
        if slot:
            target_id = target_id + "/slots/" + slot
        target = SnapshotRecoveryTarget(id=target_id)
        request = SnapshotRecoveryRequest(False,
                                          snapshot_time=time,
                                          recovery_target=target,
                                          recover_configuration=restore_config)
        if source_slot:
            return client.web_apps.recover_slot(source_resource_group,
                                                source_name, request,
                                                source_slot)
        else:
            return client.web_apps.recover(source_resource_group, source_name,
                                           request)
    elif any([source_resource_group, source_name]):
        raise CLIError(
            'usage error: --source-resource-group and --source-name must both be specified if one is used'
        )
    else:
        request = SnapshotRecoveryRequest(True,
                                          snapshot_time=time,
                                          recover_configuration=restore_config)
        if slot:
            return client.web_apps.recover_slot(resource_group, name, request,
                                                slot)
        else:
            return client.web_apps.recover(resource_group, name, request)
Пример #49
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)
Пример #50
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)

    # set default values similar to portal
    if not namespace.relay_namespace_name:
        namespace.relay_namespace_name = 'dbrelay{}'.format(random_id)
    if not namespace.storage_account_name:
        namespace.storage_account_name = 'dbstorage{}'.format(random_id)

    # name to resource id for virtual-network
    if namespace.custom_virtual_network_id is not None \
       and not is_valid_resource_id(namespace.custom_virtual_network_id):
        namespace.custom_virtual_network_id = resource_id(
            subscription=subscription_id,
            resource_group=namespace.resource_group_name,
            namespace='Microsoft.Network',
            type='virtualNetworks',
            name=namespace.custom_virtual_network_id)

    # name to resource id for load-balancer
    if namespace.load_balancer_id is not None and not is_valid_resource_id(namespace.load_balancer_id):
        namespace.load_balancer_id = resource_id(
            subscription=subscription_id,
            resource_group=namespace.resource_group_name,
            namespace='Microsoft.Network',
            type='loadBalancers',
            name=namespace.load_balancer_id)
    def test_springcloud_mysql_e2e_kvsecret(self):
        self.kwargs.update({
            'subscription': get_subscription_id(self.cli_ctx),
            'source_resource_group': 'servicelinker-test-linux-group',
            'target_resource_group': 'servicelinker-test-linux-group',
            'spring': 'servicelinker-springcloud',
            'app': 'mysql',
            'deployment': 'default',
            'server': 'servicelinker-mysql',
            'database': 'mysqlDB'
        })

        # prepare password
        user = '******'
        keyvaultUri = "https://cupertino-kv-test.vault.azure.net/secrets/TestDbPassword"

        # prepare params
        name = 'testconn'
        source_id = SOURCE_RESOURCES.get(
            RESOURCE.SpringCloud).format(**self.kwargs)
        target_id = TARGET_RESOURCES.get(RESOURCE.Mysql).format(**self.kwargs)

        # create connection
        self.cmd(
            'spring-cloud connection create mysql --connection {} --source-id {} --target-id {} '
            '--secret name={} secret-uri={} --client-type java'.format(
                name, source_id, target_id, user, keyvaultUri))

        # list connection
        connections = self.cmd(
            'spring-cloud connection list --source-id {}'.format(source_id),
            checks=[
                self.check('length(@)', 1),
                self.check('[0].authInfo.authType', 'secret'),
                self.check('[0].clientType', 'java')
            ]).get_output_in_json()
        connection_id = connections[0].get('id')

        # delete connection
        self.cmd('spring-cloud connection delete --id {} --yes'.format(
            connection_id))
Пример #52
0
def get_storage_account_id_from_blob_path(cmd,
                                          blob_path,
                                          resource_group,
                                          subscription_id=None):
    from msrestazure.tools import resource_id
    from azure.cli.core.commands.client_factory import get_subscription_id

    logger.debug('Getting storage account id for blob: %s', blob_path)

    storage_account_name = blob_path.split('.')[0].split('/')[-1]

    if not subscription_id:
        subscription_id = get_subscription_id(cmd.cli_ctx)

    storage_account_id = resource_id(subscription=subscription_id,
                                     resource_group=resource_group,
                                     namespace='Microsoft.Storage',
                                     type='storageAccounts',
                                     name=storage_account_name)

    return storage_account_id
Пример #53
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.create(resource_group_name, name, cache_to_link.name, params)
Пример #54
0
def _get_scope_for_event_subscription(
        cli_ctx,
        resource_id,
        topic_name,
        resource_group_name):
    if resource_id:
        # Resource ID is provided, use that as the scope for the event subscription.
        scope = resource_id
    elif topic_name:
        # Topic name is provided, use the topic and resource group to build a scope for the user topic
        if resource_group_name is None:
            raise CLIError("When --topic-name is specified, the --resource-group-name must also be specified.")

        scope = _get_scope(cli_ctx, resource_group_name, EVENTGRID_NAMESPACE, EVENTGRID_TOPICS, topic_name)
    elif resource_group_name:
        # Event subscription to a resource group.
        scope = _get_scope(cli_ctx, resource_group_name, RESOURCES_NAMESPACE, RESOURCE_GROUPS, resource_group_name)
    else:
        scope = _get_scope(cli_ctx, None, RESOURCES_NAMESPACE, SUBSCRIPTIONS, get_subscription_id(cli_ctx))

    return scope
Пример #55
0
def deleteDeployment(cmd, deploymentId, subscription=None):
    """Deletes a deployment.
    deploymentId: The unique id created at the time the deployment was made.
    subscription[optional]: Provides an alternate subscripton to use if desired.
    """
    if subscription is None:
        subscription = get_subscription_id(cmd.cli_ctx)
        logger.info("Using default subscription: " + subscription)
    profile = Profile(cli_ctx=cmd.cli_ctx)
    auth_token = profile.get_raw_token(subscription=subscription)
    creds = authentication.BasicTokenAuthentication(
        {'access_token': auth_token[0][1]})
    ciqsapi = ciqs_api.CiqsApi(creds=creds, base_url=api.getEndpoint())
    try:
        logger.info("Sending request.")
        deleteResponse = ciqsapi.delete_api_deployments_by_subscription_id_by_deployment_id(
            subscription, deploymentId)
    except msrest.exceptions.HttpOperationError as e:
        message = e.response.json()
        raise CLIError(message)
    return deleteResponse
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)
    else:
        raise CLIError('incorrect usage: [--subnet ID | --subnet NAME --vnet-name NAME]')
Пример #57
0
def _get_default_containerapps_location(cmd, location=None):
    if location:
        return location
    default_location = "eastus"
    providers_client = None
    try:
        providers_client = providers_client_factory(cmd.cli_ctx, get_subscription_id(cmd.cli_ctx))
        resource_types = getattr(providers_client.get("Microsoft.App"), 'resource_types', [])
        res_locations = []
        for res in resource_types:
            if res and getattr(res, 'resource_type', "") == "workspaces":
                res_locations = getattr(res, 'locations', [])

        if len(res_locations) > 0:
            location = res_locations[0].lower().replace(" ", "").replace("(", "").replace(")", "")
            if location:
                return location

    except Exception:  # pylint: disable=broad-except
        return default_location
    return default_location
Пример #58
0
def migration_delete_func(cmd,
                          client,
                          resource_group_name,
                          server_name,
                          migration_name,
                          yes=None):

    subscription_id = get_subscription_id(cmd.cli_ctx)

    if not yes:
        user_confirmation(
            "Are you sure you want to delete the migration '{0}' on target server '{1}', resource group '{2}'"
            .format(migration_name, server_name, resource_group_name))

    r = send_raw_request(
        cmd.cli_ctx, "delete",
        "https://management.azure.com/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{}/migrations/{}?api-version=2020-02-14-privatepreview"
        .format(subscription_id, resource_group_name, server_name,
                migration_name))

    return r.json()
def validate_express_route_peering(cmd, namespace):
    from msrestazure.tools import is_valid_resource_id, resource_id
    circuit = namespace.circuit_name
    peering = namespace.peering

    if not circuit and not peering:
        return

    usage_error = CLIError(
        'usage error: --peering ID | --peering NAME --circuit-name CIRCUIT')
    if not is_valid_resource_id(peering):
        namespace.peering = resource_id(
            subscription=get_subscription_id(cmd.cli_ctx),
            resource_group=namespace.resource_group_name,
            namespace='Microsoft.Network',
            type='expressRouteCircuits',
            name=circuit,
            child_type_1='peerings',
            child_name_1=peering)
    elif circuit:
        raise usage_error
Пример #60
0
def _server_restore(cmd,
                    client,
                    resource_group_name,
                    server_name,
                    parameters,
                    no_wait=False,
                    **kwargs):
    source_server = kwargs['source_server_id']

    if not is_valid_resource_id(source_server):
        if len(source_server.split('/')) == 1:
            provider = 'Microsoft.DBForMySQL' if isinstance(
                client, ServersOperations) else 'Microsoft.DBforPostgreSQL'
            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 ValueError(
                'The provided source-server {} is invalid.'.format(
                    source_server))

    parameters.properties.source_server_id = source_server

    # Here is a workaround that we don't support cross-region restore currently,
    # so the location must be set as the same as source server (not the resource group)
    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 client.create(resource_group_name,
                         server_name,
                         parameters,
                         raw=no_wait)