def process_ag_rule_create_namespace(namespace): # pylint: disable=unused-argument if namespace.address_pool and not is_valid_resource_id( namespace.address_pool): namespace.address_pool = _generate_ag_subproperty_id( namespace, 'backendAddressPools', namespace.address_pool) if namespace.http_listener and not is_valid_resource_id( namespace.http_listener): namespace.http_listener = _generate_ag_subproperty_id( namespace, 'httpListeners', namespace.http_listener) if namespace.http_settings and not is_valid_resource_id( namespace.http_settings): namespace.http_settings = _generate_ag_subproperty_id( namespace, 'backendHttpSettingsCollection', namespace.http_settings) if namespace.url_path_map and not is_valid_resource_id( namespace.url_path_map): namespace.url_path_map = _generate_ag_subproperty_id( namespace, 'urlPathMaps', namespace.url_path_map) if namespace.redirect_config and not is_valid_resource_id( namespace.redirect_config): namespace.redirect_config = _generate_ag_subproperty_id( namespace, 'redirectConfigurations', namespace.redirect_config)
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
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('artifactId')), 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('artifactId')) with self.assertRaises(CLIError): _update_artifacts({}, self.lab_resource_id) invalid_artifact = self.jdk_artifact del invalid_artifact['artifactId'] with self.assertRaises(CLIError): _update_artifacts([invalid_artifact], self.lab_resource_id)
def process_nw_packet_capture_create_namespace(namespace): get_network_watcher_from_vm(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(), 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(), 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 process_nw_test_connectivity_namespace(namespace): from azure.cli.core.commands.arm import parse_resource_id compute_client = get_mgmt_service_client(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)(namespace) if namespace.source_resource and not is_valid_resource_id(namespace.source_resource): namespace.source_resource = resource_id( subscription=get_subscription_id(), 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(), resource_group=namespace.resource_group_name, namespace='Microsoft.Compute', type='virtualMachines', name=namespace.dest_resource)
def process_nw_packet_capture_create_namespace(namespace): get_network_watcher_from_vm(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(), 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(), 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 process_nw_test_connectivity_namespace(namespace): from azure.cli.core.commands.arm import parse_resource_id compute_client = get_mgmt_service_client(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)(namespace) if namespace.source_resource and not is_valid_resource_id(namespace.source_resource): namespace.source_resource = resource_id( subscription=get_subscription_id(), 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(), resource_group=namespace.resource_group_name, namespace='Microsoft.Compute', type='virtualMachines', name=namespace.dest_resource)
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)
def process_ag_url_path_map_rule_create_namespace(namespace): # pylint: disable=unused-argument if namespace.address_pool and not is_valid_resource_id(namespace.address_pool): namespace.address_pool = _generate_ag_subproperty_id( 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( namespace, 'backendHttpSettingsCollection', namespace.http_settings)
def process_ag_url_path_map_rule_create_namespace(namespace): # pylint: disable=unused-argument if namespace.address_pool and not is_valid_resource_id(namespace.address_pool): namespace.address_pool = _generate_ag_subproperty_id( 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( namespace, 'backendHttpSettingsCollection', namespace.http_settings)
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)
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)
def test_resource_id_simple(self): rg = 'lbrg' lb = 'mylb' namespace = 'Microsoft.Network' rtype = 'loadBalancers' sub = '00000000-0000-0000-0000-000000000000' result = resource_id(resource_group=rg, name=lb, namespace=namespace, type=rtype, subscription=sub) expected = '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/lbrg/providers/Microsoft.Network/loadBalancers/mylb' self.assertTrue(is_valid_resource_id(expected)) self.assertTrue(is_valid_resource_id(result)) self.assertEqual(result, expected)
def process_ag_listener_create_namespace(namespace): # pylint: disable=unused-argument if not is_valid_resource_id(namespace.frontend_ip): namespace.frontend_ip = _generate_ag_subproperty_id( namespace, 'frontendIpConfigurations', namespace.frontend_ip) if not is_valid_resource_id(namespace.frontend_port): namespace.frontend_port = _generate_ag_subproperty_id( namespace, 'frontendPorts', namespace.frontend_port) if not is_valid_resource_id(namespace.ssl_cert): namespace.ssl_cert = _generate_ag_subproperty_id( namespace, 'sslCertificates', namespace.ssl_cert)
def process_ag_listener_create_namespace(namespace): # pylint: disable=unused-argument if namespace.frontend_ip and not is_valid_resource_id(namespace.frontend_ip): namespace.frontend_ip = _generate_ag_subproperty_id( 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( 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( namespace, 'sslCertificates', namespace.ssl_cert)
def test_resource_id_with_child(self): rg = 'lbrg' lb = 'mylb' namespace = 'Microsoft.Network' rtype = 'loadBalancers' bep = 'mybep' bep_type = 'backendAddressPools' sub = '00000000-0000-0000-0000-000000000000' result = resource_id(name=lb, resource_group=rg, namespace=namespace, type=rtype, subscription=sub, child_type=bep_type, child_name=bep) expected = '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/lbrg/providers/Microsoft.Network/loadBalancers/mylb/backendAddressPools/mybep' self.assertTrue(is_valid_resource_id(expected)) self.assertTrue(is_valid_resource_id(result)) self.assertEqual(result, expected)
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)
def test_resource_id_simple(self): rg = 'lbrg' lb = 'mylb' namespace = 'Microsoft.Network' rtype = 'loadBalancers' sub = '00000000-0000-0000-0000-000000000000' result = resource_id(resource_group=rg, name=lb, namespace=namespace, type=rtype, subscription=sub) expected = '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/lbrg/providers/Microsoft.Network/loadBalancers/mylb' self.assertTrue(is_valid_resource_id(expected)) self.assertTrue(is_valid_resource_id(result)) self.assertEqual(result, expected)
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())
def list_policy_assignment(disable_scope_strict_match=None, resource_group_name=None, scope=None): policy_client = _resource_policy_client_factory() if scope and not is_valid_resource_id(scope): parts = scope.strip('/').split('/') if len(parts) == 4: resource_group_name = parts[3] elif len(parts) == 2: #rarely used, but still verify if parts[1].lower() != policy_client.config.subscription_id.lower(): raise CLIError("Please use current active subscription's id") else: err = "Invalid scope '{}', it should point to a resource group or a resource" raise CLIError(err.format(scope)) scope = None _scope = _build_policy_scope(policy_client.config.subscription_id, resource_group_name, scope) if resource_group_name: result = policy_client.policy_assignments.list_for_resource_group(resource_group_name) elif scope: #pylint: disable=redefined-builtin id = parse_resource_id(scope) parent_resource_path = '' if not id.get('child_name') else (id['type'] + '/' + id['name']) resource_type = id.get('child_type') or id['type'] resource_name = id.get('child_name') or id['name'] result = policy_client.policy_assignments.list_for_resource( id['resource_group'], id['namespace'], parent_resource_path, resource_type, resource_name) else: result = policy_client.policy_assignments.list() if not disable_scope_strict_match: result = [i for i in result if _scope.lower() == i.scope.lower()] return result
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)
def move_resource(ids, destination_group, destination_subscription_id=None): '''Moves resources from one resource group to another(can be under different subscription) :param ids: the space separated resource ids to be moved :param destination_group: the destination resource group name :param destination_subscription_id: the destination subscription identifier ''' from azure.cli.core.commands.arm import resource_id #verify all resource ids are valid and under the same group resources = [] for i in ids: if is_valid_resource_id(i): resources.append(parse_resource_id(i)) else: raise CLIError('Invalid id "{}", as it has no group or subscription field'.format(i)) if len(set([r['subscription'] for r in resources])) > 1: raise CLIError('All resources should be under the same subscription') if len(set([r['resource_group'] for r in resources])) > 1: raise CLIError('All resources should be under the same group') rcf = _resource_client_factory() target = resource_id(subscription=(destination_subscription_id or rcf.config.subscription_id), resource_group=destination_group) return rcf.resources.move_resources(resources[0]['resource_group'], ids, target)
def create_webapp(resource_group, name, plan): client = web_client_factory() if is_valid_resource_id(plan): plan = parse_resource_id(plan)['name'] location = _get_location_from_app_service_plan(client, resource_group, plan) webapp_def = Site(server_farm_id=plan, location=location) return client.sites.create_or_update_site(resource_group, name, webapp_def)
def simple_validator(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(), resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='virtualNetworks', name=namespace.virtual_network_name, child_type='subnets', child_name=namespace.subnet)
def list_policy_assignment(disable_scope_strict_match=None, resource_group_name=None, scope=None): policy_client = _resource_policy_client_factory() if scope and not is_valid_resource_id(scope): parts = scope.strip('/').split('/') if len(parts) == 4: resource_group_name = parts[3] elif len(parts) == 2: #rarely used, but still verify if parts[1].lower() != policy_client.config.subscription_id.lower(): raise CLIError("Please use current active subscription's id") else: err = "Invalid scope '{}', it should point to a resource group or a resource" raise CLIError(err.format(scope)) scope = None _scope = _build_policy_scope(policy_client.config.subscription_id, resource_group_name, scope) if resource_group_name: result = policy_client.policy_assignments.list_for_resource_group(resource_group_name) elif scope: #pylint: disable=redefined-builtin id = parse_resource_id(scope) parent_resource_path = '' if not id.get('child_name') else (id['type'] + '/' + id['name']) resource_type = id.get('child_type') or id['type'] resource_name = id.get('child_name') or id['name'] result = policy_client.policy_assignments.list_for_resource( id['resource_group'], id['namespace'], parent_resource_path, resource_type, resource_name) else: result = policy_client.policy_assignments.list() if not disable_scope_strict_match: result = [i for i in result if _scope.lower() == i.scope.lower()] return result
def _use_custom_image(namespace): """ Retrieve custom image from lab and update namespace """ if is_valid_resource_id(namespace.image): namespace.custom_image_id = namespace.image else: custom_image_operation = get_devtestlabs_management_client(None).custom_images odata_filter = ODATA_NAME_FILTER.format(namespace.image) custom_images = list(custom_image_operation.list(namespace.resource_group, 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
def validate_plan_arg(namespace): from ._client_factory import web_client_factory namespace.create_plan = False if namespace.plan: from azure.cli.core.commands.arm import is_valid_resource_id if not is_valid_resource_id(namespace.plan): from msrestazure.azure_exceptions import CloudError client = web_client_factory() try: client.app_service_plans.get(namespace.resource_group_name, namespace.plan) except CloudError: namespace.create_plan = True else: client = web_client_factory() result = client.app_service_plans.list_by_resource_group( namespace.resource_group_name) existing_plan = next( (x for x in result if match_plan_location(x, namespace.location) and namespace.is_linux == (x.kind == 'linux')), None) if existing_plan: namespace.plan = existing_plan.id else: namespace.create_plan = True namespace.plan = namespace.name + '_plan' if not namespace.create_plan and (namespace.sku or namespace.number_of_workers): raise CLIError( 'Usage error: argument values for --sku or --number-of-workers will ' 'be ignored, as the new web will be created using an existing ' 'plan {}. Please use --plan to specify a new plan'.format( namespace.plan))
def simple_validator(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(), resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='virtualNetworks', name=namespace.virtual_network_name, child_type='subnets', child_name=namespace.subnet)
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)
def add_network_rule( client, resource_group_name, storage_account_name, action='Allow', subnet=None, vnet_name=None, # pylint: disable=unused-argument ip_address=None): sa = client.get_properties(resource_group_name, storage_account_name) rules = sa.network_acls if subnet: from azure.cli.core.commands.arm import is_valid_resource_id if not is_valid_resource_id(subnet): raise CLIError( "Expected fully qualified resource ID: got '{}'".format( subnet)) VirtualNetworkRule = get_sdk(ResourceType.MGMT_STORAGE, 'VirtualNetworkRule', mod='models') if not rules.virtual_network_rules: rules.virtual_network_rules = [] rules.virtual_network_rules.append( VirtualNetworkRule(subnet, action=action)) if ip_address: IpRule = get_sdk(ResourceType.MGMT_STORAGE, 'IPRule', mod='models') if not rules.ip_rules: rules.ip_rules = [] rules.ip_rules.append(IpRule(ip_address, action=action)) StorageAccountUpdateParameters = get_sdk(ResourceType.MGMT_STORAGE, 'StorageAccountUpdateParameters', mod='models') params = StorageAccountUpdateParameters(network_acls=rules) return client.update(resource_group_name, storage_account_name, params)
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)
def move_resource(ids, destination_group, destination_subscription_id=None): '''Moves resources from one resource group to another(can be under different subscription) :param ids: the space separated resource ids to be moved :param destination_group: the destination resource group name :param destination_subscription_id: the destination subscription identifier ''' from azure.cli.core.commands.arm import resource_id #verify all resource ids are valid and under the same group resources = [] for i in ids: if is_valid_resource_id(i): resources.append(parse_resource_id(i)) else: raise CLIError('Invalid id "{}", as it has no group or subscription field'.format(i)) if len(set([r['subscription'] for r in resources])) > 1: raise CLIError('All resources should be under the same subscription') if len(set([r['resource_group'] for r in resources])) > 1: raise CLIError('All resources should be under the same group') rcf = _resource_client_factory() target = resource_id(subscription=(destination_subscription_id or rcf.config.subscription_id), resource_group=destination_group) return rcf.resources.move_resources(resources[0]['resource_group'], ids, target)
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())
def create_webapp(resource_group_name, name, plan): client = web_client_factory() if is_valid_resource_id(plan): plan = parse_resource_id(plan)['name'] location = _get_location_from_app_service_plan(client, resource_group_name, plan) webapp_def = Site(server_farm_id=plan, location=location) poller = client.web_apps.create_or_update(resource_group_name, name, webapp_def) return AppServiceLongRunningOperation()(poller)
def process_ag_url_path_map_create_namespace(namespace): # pylint: disable=unused-argument if namespace.default_address_pool and not is_valid_resource_id(namespace.default_address_pool): namespace.default_address_pool = _generate_ag_subproperty_id( namespace, 'backendAddressPools', namespace.default_address_pool) if namespace.default_http_settings and not is_valid_resource_id( namespace.default_http_settings): namespace.default_http_settings = _generate_ag_subproperty_id( namespace, 'backendHttpSettingsCollection', namespace.default_http_settings) if namespace.default_redirect_config and not is_valid_resource_id( namespace.default_redirect_config): namespace.default_redirect_config = _generate_ag_subproperty_id( namespace, 'redirectConfigurations', namespace.default_redirect_config) if hasattr(namespace, 'rule_name'): process_ag_url_path_map_rule_create_namespace(namespace)
def create_webapp(resource_group_name, name, plan): client = web_client_factory() if is_valid_resource_id(plan): plan = parse_resource_id(plan)['name'] location = _get_location_from_app_service_plan(client, resource_group_name, plan) webapp_def = Site(server_farm_id=plan, location=location) poller = client.web_apps.create_or_update(resource_group_name, name, webapp_def) return AppServiceLongRunningOperation()(poller)
def process_ag_url_path_map_create_namespace(namespace): # pylint: disable=unused-argument if namespace.default_address_pool and not is_valid_resource_id(namespace.default_address_pool): namespace.default_address_pool = _generate_ag_subproperty_id( namespace, 'backendAddressPools', namespace.default_address_pool) if namespace.default_http_settings and not is_valid_resource_id( namespace.default_http_settings): namespace.default_http_settings = _generate_ag_subproperty_id( namespace, 'backendHttpSettingsCollection', namespace.default_http_settings) if namespace.default_redirect_config and not is_valid_resource_id( namespace.default_redirect_config): namespace.default_redirect_config = _generate_ag_subproperty_id( namespace, 'redirectConfigurations', namespace.default_redirect_config) if hasattr(namespace, 'rule_name'): process_ag_url_path_map_rule_create_namespace(namespace)
def create_webapp(resource_group, name, plan): client = web_client_factory() if is_valid_resource_id(plan): plan = parse_resource_id(plan)['name'] location = _get_location_from_app_service_plan(client, resource_group, plan) webapp_def = Site(server_farm_id=plan, location=location) return client.sites.create_or_update_site(resource_group, name, webapp_def)
def _get_resource_id(val, resource_group, resource_type, resource_namespace): if is_valid_resource_id(val): return val else: return resource_id(name=val, resource_group=resource_group, namespace=resource_namespace, type=resource_type, subscription=get_subscription_id())
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(), resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='publicIPAddresses', name=public_ip)
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(), resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='publicIPAddresses', name=public_ip)
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)
def _get_resource_name_and_rg(resource_group_name, name_or_id): if is_valid_resource_id(name_or_id): id_parts = parse_resource_id(name_or_id) name = id_parts['name'] resource_group = id_parts['resource_group'] else: name = name_or_id resource_group = resource_group_name return name, resource_group
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)
def _validate_vm_vmss_create_vnet(namespace, for_scale_set=False): vnet = namespace.vnet_name subnet = namespace.subnet rg = namespace.resource_group_name location = namespace.location nics = getattr(namespace, 'nics', None) if not vnet and not subnet and not nics: logger.debug('no subnet specified. Attempting to find an existing Vnet and subnet...') # if nothing specified, try to find an existing vnet and subnet in the target resource group client = get_network_client().virtual_networks # find VNET in target resource group that matches the VM's location with a matching subnet for vnet_match in (v for v in client.list(rg) if v.location == location and v.subnets): # 1 - find a suitable existing vnet/subnet result = None if not for_scale_set: result = next((s for s in vnet_match.subnets if s.name.lower() != 'gatewaysubnet'), None) else: def _check_subnet(s): if s.name.lower() == 'gatewaysubnet': return False subnet_mask = s.address_prefix.split('/')[-1] return _subnet_capacity_check(subnet_mask, namespace.instance_count) result = next((s for s in vnet_match.subnets if _check_subnet(s)), None) if not result: continue namespace.subnet = result.name namespace.vnet_name = vnet_match.name namespace.vnet_type = 'existing' logger.debug("existing vnet '%s' and subnet '%s' found", namespace.vnet_name, namespace.subnet) return if subnet: subnet_is_id = is_valid_resource_id(subnet) if (subnet_is_id and vnet) or (not subnet_is_id and not vnet): raise CLIError("incorrect '--subnet' usage: --subnet SUBNET_ID | " "--subnet SUBNET_NAME --vnet-name VNET_NAME") subnet_exists = \ check_existence(subnet, rg, 'Microsoft.Network', 'subnets', vnet, 'virtualNetworks') if subnet_is_id and not subnet_exists: raise CLIError("Subnet '{}' does not exist.".format(subnet)) elif subnet_exists: # 2 - user specified existing vnet/subnet namespace.vnet_type = 'existing' logger.debug("using specified vnet '%s' and subnet '%s'", namespace.vnet_name, namespace.subnet) return # 3 - create a new vnet/subnet namespace.vnet_type = 'new' logger.debug('no suitable subnet found. One will be created.')
def _validate_vm_create_vnet(namespace, for_scale_set=False): vnet = namespace.vnet_name subnet = namespace.subnet rg = namespace.resource_group_name location = namespace.location nics = getattr(namespace, 'nics', None) if not vnet and not subnet and not nics: # pylint: disable=too-many-nested-blocks # if nothing specified, try to find an existing vnet and subnet in the target resource group from azure.mgmt.network import NetworkManagementClient from azure.cli.core.commands.client_factory import get_mgmt_service_client client = get_mgmt_service_client( NetworkManagementClient).virtual_networks # find VNET in target resource group that matches the VM's location with a matching subnet for vnet_match in (v for v in client.list(rg) if v.location == location and v.subnets): # 1 - find a suitable existing vnet/subnet result = None if not for_scale_set: result = next((s for s in vnet_match.subnets if s.name.lower() != 'gatewaysubnet'), None) else: for s in vnet_match.subnets: if s.name.lower() != 'gatewaysubnet': subnet_mask = s.address_prefix.split('/')[-1] if _subnet_capacity_check(subnet_mask, namespace.instance_count): result = s break if not result: continue namespace.subnet = result.name namespace.vnet_name = vnet_match.name namespace.vnet_type = 'existing' return if subnet: subnet_is_id = is_valid_resource_id(subnet) if (subnet_is_id and vnet) or (not subnet_is_id and not vnet): raise CLIError("incorrect '--subnet' usage: --subnet SUBNET_ID | " "--subnet SUBNET_NAME --vnet-name VNET_NAME") subnet_exists = \ check_existence(subnet, rg, 'Microsoft.Network', 'subnets', vnet, 'virtualNetworks') if subnet_is_id and not subnet_exists: raise CLIError("Subnet '{}' does not exist.".format(subnet)) elif subnet_exists: # 2 - user specified existing vnet/subnet namespace.vnet_type = 'existing' return # 3 - create a new vnet/subnet namespace.vnet_type = 'new'
def _validate_vm_vmss_create_vnet(namespace, for_scale_set=False): vnet = namespace.vnet_name subnet = namespace.subnet rg = namespace.resource_group_name location = namespace.location nics = getattr(namespace, 'nics', None) if not vnet and not subnet and not nics: logger.debug('no subnet specified. Attempting to find an existing Vnet and subnet...') # if nothing specified, try to find an existing vnet and subnet in the target resource group client = get_network_client().virtual_networks # find VNET in target resource group that matches the VM's location with a matching subnet for vnet_match in (v for v in client.list(rg) if v.location == location and v.subnets): # 1 - find a suitable existing vnet/subnet result = None if not for_scale_set: result = next((s for s in vnet_match.subnets if s.name.lower() != 'gatewaysubnet'), None) else: def _check_subnet(s): if s.name.lower() == 'gatewaysubnet': return False subnet_mask = s.address_prefix.split('/')[-1] return _subnet_capacity_check(subnet_mask, namespace.instance_count) result = next((s for s in vnet_match.subnets if _check_subnet(s)), None) if not result: continue namespace.subnet = result.name namespace.vnet_name = vnet_match.name namespace.vnet_type = 'existing' logger.debug("existing vnet '%s' and subnet '%s' found", namespace.vnet_name, namespace.subnet) return if subnet: subnet_is_id = is_valid_resource_id(subnet) if (subnet_is_id and vnet) or (not subnet_is_id and not vnet): raise CLIError("incorrect '--subnet' usage: --subnet SUBNET_ID | " "--subnet SUBNET_NAME --vnet-name VNET_NAME") subnet_exists = \ check_existence(subnet, rg, 'Microsoft.Network', 'subnets', vnet, 'virtualNetworks') if subnet_is_id and not subnet_exists: raise CLIError("Subnet '{}' does not exist.".format(subnet)) elif subnet_exists: # 2 - user specified existing vnet/subnet namespace.vnet_type = 'existing' logger.debug("using specified vnet '%s' and subnet '%s'", namespace.vnet_name, namespace.subnet) return # 3 - create a new vnet/subnet namespace.vnet_type = 'new' logger.debug('no suitable subnet found. One will be created.')
def process_nw_flow_log_set_namespace(namespace): if namespace.storage_account and not is_valid_resource_id(namespace.storage_account): namespace.storage_account = resource_id( subscription=get_subscription_id(), resource_group=namespace.resource_group_name, namespace='Microsoft.Storage', type='storageAccounts', name=namespace.storage_account) process_nw_flow_log_show_namespace(namespace)
def _get_nic_id(val, resource_group, subscription): if is_valid_resource_id(val): return val else: return resource_id( name=val, resource_group=resource_group, namespace='Microsoft.Network', type='networkInterfaces', subscription=subscription)
def _get_resource_id(val, resource_group, resource_type, resource_namespace): if is_valid_resource_id(val): return val else: return resource_id( name=val, resource_group=resource_group, namespace=resource_namespace, type=resource_type, subscription=get_subscription_id())
def validate_target_listener(namespace): if namespace.target_listener and not is_valid_resource_id(namespace.target_listener): namespace.target_listener = resource_id( subscription=get_subscription_id(), resource_group=namespace.resource_group_name, name=namespace.application_gateway_name, namespace='Microsoft.Network', type='applicationGateways', child_type='httpListeners', child_name=namespace.target_listener)
def _validate_name_or_id(namespace, value, resource_type): if not is_valid_resource_id(value): subscription = getattr(namespace, 'subscription', get_subscription_id()) return resource_id(subscription=subscription, resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type=resource_type, name=value) return value
def validate_target_listener(namespace): if namespace.target_listener and not is_valid_resource_id(namespace.target_listener): namespace.target_listener = resource_id( subscription=get_subscription_id(), resource_group=namespace.resource_group_name, name=namespace.application_gateway_name, namespace='Microsoft.Network', type='applicationGateways', child_type='httpListeners', child_name=namespace.target_listener)
def process_nw_flow_log_set_namespace(namespace): if namespace.storage_account and not is_valid_resource_id(namespace.storage_account): namespace.storage_account = resource_id( subscription=get_subscription_id(), resource_group=namespace.resource_group_name, namespace='Microsoft.Storage', type='storageAccounts', name=namespace.storage_account) process_nw_flow_log_show_namespace(namespace)
def _validate_name_or_id(namespace, value, resource_type): if not is_valid_resource_id(value): subscription = getattr(namespace, 'subscription', get_subscription_id()) return resource_id( subscription=subscription, resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type=resource_type, name=value) return value
def process_ag_rule_create_namespace(namespace): # pylint: disable=unused-argument if namespace.address_pool and not is_valid_resource_id(namespace.address_pool): namespace.address_pool = _generate_ag_subproperty_id( namespace, 'backendAddressPools', namespace.address_pool) if namespace.http_listener and not is_valid_resource_id(namespace.http_listener): namespace.http_listener = _generate_ag_subproperty_id( namespace, 'httpListeners', namespace.http_listener) if namespace.http_settings and not is_valid_resource_id(namespace.http_settings): namespace.http_settings = _generate_ag_subproperty_id( namespace, 'backendHttpSettingsCollection', namespace.http_settings) if namespace.url_path_map and not is_valid_resource_id(namespace.url_path_map): namespace.url_path_map = _generate_ag_subproperty_id( namespace, 'urlPathMaps', namespace.url_path_map) if namespace.redirect_config and not is_valid_resource_id(namespace.redirect_config): namespace.redirect_config = _generate_ag_subproperty_id( namespace, 'redirectConfigurations', namespace.redirect_config)
def simple_validator(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(), resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='virtualNetworks', name=namespace.virtual_network)
def simple_validator(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(), resource_group=namespace.resource_group_name, namespace='Microsoft.Network', type='networkSecurityGroups', name=namespace.network_security_group)