def acr_agentpool_delete(cmd, client, agent_pool_name, registry_name, no_wait=False, yes=False, resource_group_name=None): _, resource_group_name = validate_managed_registry( cmd, registry_name, resource_group_name) user_confirmation("Are you sure you want to delete the agentpool '{}' in registry '{}'?".format( agent_pool_name, registry_name), yes) try: response = client.begin_delete(resource_group_name=resource_group_name, registry_name=registry_name, agent_pool_name=agent_pool_name) if no_wait: logger.warning("Started to delete the agent pool '%s': %s", agent_pool_name, response.status()) return response # Since agent pool is a tracked resource in arm, arm also pings the async deletion api at the # same time to get the status. If arm gets the 200 status first and knows that the resource is deleted, # it marks the resource as deleted and stop routing further requests to the resource including the # async deletion status api. Hence arm will directly return 404. Consider this as successful delete. from ._agentpool_polling import delete_agentpool_with_polling return delete_agentpool_with_polling(cmd, client, agent_pool_name, registry_name, resource_group_name) except ValidationError as e: raise CLIError(e)
def _delete_manifest_confirmation(login_server, username, password, repository, tag, manifest, yes): # Always query manifest if it is empty manifest = manifest or _get_manifest_digest(login_server=login_server, repository=repository, tag=tag, username=username, password=password) tags = _obtain_data_from_registry(login_server=login_server, path=_get_tag_path(repository), username=username, password=password, result_index='tags') filter_by_manifest = [x['name'] for x in tags if manifest == x['digest']] message = "This operation will delete the manifest '{}'".format(manifest) if filter_by_manifest: images = ", ".join( ["'{}:{}'".format(repository, str(x)) for x in filter_by_manifest]) message += " and all the following images: {}".format(images) if yes: logger.warning(message) return manifest user_confirmation( "{}.\nAre you sure you want to continue?".format(message)) return manifest
def export_blueprint_with_artifacts(cmd, client, blueprint_name, output_path, skip_confirmation=False, management_group=None, subscription=None, scope=None, **kwargs): # match folder structure required for import_blueprint_with_artifact blueprint_parent_folder = os.path.join(os.path.abspath(output_path), blueprint_name) blueprint_file_location = os.path.join(blueprint_parent_folder, 'blueprint.json') artifacts_location = os.path.join(blueprint_parent_folder, 'artifacts') if os.path.exists(blueprint_parent_folder) and os.listdir(blueprint_parent_folder) and not skip_confirmation: user_prompt = f"That directory already contains a folder with the name {blueprint_name}. Would you like to continue?" user_confirmation(user_prompt) try: blueprint = client.get(scope=scope, blueprint_name=blueprint_name) serialized_blueprint = blueprint.serialize() except CloudError as error: raise CLIError('Unable to export blueprint: {}'.format(str(error.message))) os.makedirs(artifacts_location, exist_ok=True) with open(blueprint_file_location, 'w') as f: json.dump(serialized_blueprint, f, indent=4) artifact_client = cf_artifacts(cmd.cli_ctx) available_artifacts = artifact_client.list(scope=scope, blueprint_name=blueprint_name) for artifact in available_artifacts: artifact_file_location = os.path.join(artifacts_location, artifact.name + '.json') serialized_artifact = artifact.serialize() with open(artifact_file_location, 'w') as f: json.dump(serialized_artifact, f, indent=4) return blueprint
def database_delete_func(client, resource_group_name=None, server_name=None, database_name=None, yes=None): result = None if resource_group_name is None or server_name is None or database_name is None: raise CLIError( "Incorrect Usage : Deleting a database needs resource-group, server-name and database-name. " "If your parameter persistence is turned ON, make sure these three parameters exist in " "persistent parameters using \'az config param-persist show\'. " "If your parameter persistence is turned OFF, consider passing them explicitly." ) if not yes: user_confirmation( "Are you sure you want to delete the database '{0}' of server '{1}'" .format(database_name, server_name), yes=yes) try: result = client.begin_delete(resource_group_name, server_name, database_name) except Exception as ex: # pylint: disable=broad-except logger.error(ex) return result
def delete_configstore(cmd, client, name, resource_group_name=None, yes=False): if resource_group_name is None: resource_group_name, _ = resolve_store_metadata(cmd, name) confirmation_message = "Are you sure you want to delete the App Configuration: {}".format( name) user_confirmation(confirmation_message, yes) return client.begin_delete(resource_group_name, name)
def user_confirmation_factory( cmd, yes, message="Are you sure you want to perform this operation?"): if cmd.cli_ctx.config.getboolean('core', 'disable_confirm_prompt', fallback=False): return user_confirmation(message, yes=yes)
def server_delete_func(cmd, client, resource_group_name=None, server_name=None, yes=None): result = None # default return value if not yes: user_confirmation( "Are you sure you want to delete the server '{0}' in resource group '{1}'" .format(server_name, resource_group_name), yes=yes) try: result = client.begin_delete(resource_group_name, server_name) if cmd.cli_ctx.local_context.is_on: local_context_file = cmd.cli_ctx.local_context._get_local_context_file( ) # pylint: disable=protected-access local_context_file.remove_option('mysql flexible-server', 'server_name') local_context_file.remove_option('mysql flexible-server', 'administrator_login') local_context_file.remove_option('mysql flexible-server', 'database_name') except Exception as ex: # pylint: disable=broad-except logger.error(ex) raise CLIError(ex) return result
def unlock_key(cmd, key, label=None, name=None, connection_string=None, yes=False, auth_mode="key", endpoint=None): azconfig_client = get_appconfig_data_client(cmd, name, connection_string, auth_mode, endpoint) retry_times = 3 retry_interval = 1 for i in range(0, retry_times): try: retrieved_kv = azconfig_client.get_configuration_setting(key=key, label=label) except ResourceNotFoundError: raise CLIError("Key '{}' with label '{}' does not exist.".format(key, label)) except HttpResponseError as exception: raise CLIError("Failed to retrieve key-values from config store. " + str(exception)) confirmation_message = "Are you sure you want to unlock the key '{}' with label '{}'".format(key, label) user_confirmation(confirmation_message, yes) try: new_kv = azconfig_client.set_read_only(retrieved_kv, read_only=False, match_condition=MatchConditions.IfNotModified) return convert_configurationsetting_to_keyvalue(new_kv) except HttpResponseError as exception: if exception.status_code == StatusCodes.PRECONDITION_FAILED: logger.debug('Retrying unlock operation %s times with exception: concurrent setting operations', i + 1) time.sleep(retry_interval) else: raise CLIError("Failed to unlock the key-value due to an exception: " + str(exception)) except Exception as exception: raise CLIError("Failed to unlock the key-value due to an exception: " + str(exception)) raise CLIError("Failed to unlock the key '{}' with label '{}' due to a conflicting operation.".format(key, label))
def __clear_filter(azconfig_client, feature, label=None, yes=False): key = FeatureFlagConstants.FEATURE_FLAG_PREFIX + feature retry_times = 3 retry_interval = 1 for i in range(0, retry_times): try: retrieved_kv = azconfig_client.get_configuration_setting(key=key, label=label) except ResourceNotFoundError: raise CLIError("Feature flag '{}' with label '{}' not found.".format(feature, label)) except HttpResponseError as exception: raise CLIError("Failed to retrieve feature flags from config store. " + str(exception)) try: if retrieved_kv is None or retrieved_kv.content_type != FeatureFlagConstants.FEATURE_FLAG_CONTENT_TYPE: raise CLIError( "The feature flag {} does not exist.".format(feature)) # we make sure that value retrieved is a valid json and only has the fields supported by backend. # if it's invalid, we catch appropriate exception that contains # detailed message feature_flag_value = map_keyvalue_to_featureflagvalue(retrieved_kv) # These fields will never be missing because we validate that # in map_keyvalue_to_featureflagvalue feature_filters = feature_flag_value.conditions['client_filters'] # create a deep copy of the filters to display to the user # after deletion display_filters = [] if feature_filters: confirmation_message = "Are you sure you want to delete all filters for feature '{0}'?\n".format(feature) user_confirmation(confirmation_message, yes) display_filters = copy.deepcopy(feature_filters) # clearing feature_filters list for python 2.7 compatibility del feature_filters[:] __update_existing_key_value(azconfig_client=azconfig_client, retrieved_kv=retrieved_kv, updated_value=json.dumps(feature_flag_value, default=lambda o: o.__dict__, ensure_ascii=False)) return display_filters except HttpResponseError as exception: if exception.status_code == StatusCodes.PRECONDITION_FAILED: logger.debug('Retrying feature enable operation %s times with exception: concurrent setting operations', i + 1) time.sleep(retry_interval) else: raise CLIError(str(exception)) except Exception as exception: raise CLIError(str(exception)) raise CLIError( "Failed to delete filters for the feature flag '{}' due to a conflicting operation.".format(feature))
def acr_connected_registry_delete(cmd, client, connected_registry_name, registry_name, cleanup=False, yes=False, resource_group_name=None): _, resource_group_name = validate_managed_registry(cmd, registry_name, resource_group_name) extraMsg = "" if not cleanup: extraMsg = " without cleanup flag enabled" user_confirmation( "Are you sure you want to delete the connected registry '{}' in '{}'{}?" .format(connected_registry_name, registry_name, extraMsg), yes) try: connected_registry = acr_connected_registry_show( cmd, client, connected_registry_name, registry_name, resource_group_name) result = client.begin_delete(resource_group_name, registry_name, connected_registry_name) sync_token = get_token_from_id( cmd, connected_registry.parent.sync_properties.token_id) sync_token_name = sync_token.name sync_scope_map_name = sync_token.scope_map_id.split('/scopeMaps/')[1] if cleanup: from .token import acr_token_delete from .scope_map import acr_scope_map_delete token_client = cf_acr_tokens(cmd.cli_ctx) scope_map_client = cf_acr_scope_maps(cmd.cli_ctx) # Delete target sync scope map and token. acr_token_delete(cmd, token_client, registry_name, sync_token_name, yes, resource_group_name) acr_scope_map_delete(cmd, scope_map_client, registry_name, sync_scope_map_name, yes, resource_group_name) # Cleanup gateway permissions from ancestors connected_registry_list = list( client.list(resource_group_name, registry_name)) family_tree, _ = _get_family_tree(connected_registry_list, None) _update_ancestor_permissions(cmd, family_tree, resource_group_name, registry_name, connected_registry.parent.id, connected_registry_name, remove_access=True) else: msg = "Connected registry successfully deleted. Please cleanup your sync tokens and scope maps. " + \ "Run the following commands for cleanup: \n\t" + \ "az acr token delete -n {} -r {} --yes\n\t".format(sync_token_name, registry_name) + \ "az acr scope-map delete -n {} -r {} --yes\n".format(sync_scope_map_name, registry_name) + \ "Run the following command on all ascendency to remove the deleted registry gateway access: \n\t" + \ "az acr scope-map update -n <scope-map-name> -r {} --remove-gateway {}".format( registry_name, " ".join([connected_registry_name] + DEFAULT_GATEWAY_SCOPE)) logger.warning(msg) return result except ValidationError as e: raise CLIError(e)
def purge_deleted_configstore(cmd, client, name, location=None, yes=False): if location is None: _, location = resolve_deleted_store_metadata(cmd, name) confirmation_message = "This operation will permanently delete App Configuration and it's contents.\nAre you sure you want to purge the App Configuration: {}".format( name) user_confirmation(confirmation_message, yes) return client.begin_purge_deleted(config_store_name=name, location=location)
def turn_local_context_off(cmd, yes=False): if cmd.cli_ctx.local_context.is_on(): from azure.cli.core.util import user_confirmation dir_path = cmd.cli_ctx.local_context.current_turn_on_dir() user_confirmation('Local context in {} will be removed and can\'t be recovered. Are you sure you want to ' 'continue this operation ?'.format(dir_path), yes) cmd.cli_ctx.local_context.turn_off() else: raise CLIError('local context is not turned on in {} and all its parent directories'.format(os.getcwd()))
def _create_and_verify_resource_group(resource_client, resource_group, location, yes): if not resource_client.resource_groups.check_existence(resource_group): logger.warning( "Provided resource group in the resource ID doesn't exist.") user_confirmation( "Do you want to create a new resource group {0}".format( resource_group), yes=yes) resource_client.resource_groups.create_or_update( resource_group, {'location': location})
def acr_taskrun_delete(cmd, client, taskrun_name, registry_name, resource_group_name=None, yes=False): _, resource_group_name = validate_managed_registry( cmd, registry_name, resource_group_name, TASKRUN_NOT_SUPPORTED) user_confirmation("Are you sure you want to delete the taskrun '{}' ".format(taskrun_name), yes) return client.begin_delete(resource_group_name, registry_name, taskrun_name)
def acr_delete(cmd, client, registry_name, resource_group_name=None, yes=False): user_confirmation( "Are you sure you want to delete the registry '{}'?".format( registry_name), yes) resource_group_name = get_resource_group_name_by_registry_name( cmd.cli_ctx, registry_name, resource_group_name) return client.delete(resource_group_name, registry_name)
def create_autoscale(cmd, client, resource_group_name, cluster_name, type, min_workernode_count=None, max_workernode_count=None, timezone=None, days=None, time=None, workernode_count=None, no_wait=False, yes=False): from azure.mgmt.hdinsight.models import Autoscale, AutoscaleCapacity, AutoscaleRecurrence, AutoscaleSchedule, \ AutoscaleTimeAndCapacity, AutoscaleConfigurationUpdateParameter, RoleName load_based_type = "Load" schedule_based_type = "Schedule" autoscale_configuration = None if type.lower() == load_based_type.lower(): if not all([min_workernode_count, max_workernode_count]): raise CLIError( 'When the --type is Load, both --min-workernode-count and --max-workernode-count should be specified.' ) autoscale_configuration = Autoscale(capacity=AutoscaleCapacity( min_instance_count=min_workernode_count, max_instance_count=max_workernode_count)) elif type.lower() == schedule_based_type.lower(): if not all([timezone, days, time, workernode_count]): raise CLIError( 'When the --type is Schedule, all of the --timezone, --days, --time, ' '--workernode-count should be specified.') autoscale_configuration = Autoscale(recurrence=AutoscaleRecurrence( time_zone=timezone, schedule=[ AutoscaleSchedule(days=days, time_and_capacity=AutoscaleTimeAndCapacity( time=time, min_instance_count=workernode_count, max_instance_count=workernode_count)) ])) user_confirmation( "This operation will override previous autoscale configuration. " "Are you sure you want to perform this operation", yes) autoscale_configuration_update_parameter = AutoscaleConfigurationUpdateParameter( autoscale=autoscale_configuration) return sdk_no_wait(no_wait, client.begin_update_auto_scale_configuration, resource_group_name, cluster_name, RoleName.WORKERNODE, autoscale_configuration_update_parameter)
def delete_feature(cmd, feature, name=None, label=None, yes=False, connection_string=None, auth_mode="key", endpoint=None): azconfig_client = get_appconfig_data_client(cmd, name, connection_string, auth_mode, endpoint) retrieved_keyvalues = __list_all_keyvalues(azconfig_client, feature=feature, label=SearchFilterOptions.EMPTY_LABEL if label is None else label) confirmation_message = "Found '{}' feature flags matching the specified feature and label. Are you sure you want to delete these feature flags?".format(len(retrieved_keyvalues)) user_confirmation(confirmation_message, yes) deleted_kvs = [] exception_messages = [] for entry in retrieved_keyvalues: feature_name = entry.key[len(FeatureFlagConstants.FEATURE_FLAG_PREFIX):] try: deleted_kv = azconfig_client.delete_configuration_setting(key=entry.key, label=entry.label, etag=entry.etag, match_condition=MatchConditions.IfNotModified) deleted_kvs.append(convert_configurationsetting_to_keyvalue(deleted_kv)) except ResourceReadOnlyError: exception = "Failed to delete read-only feature '{}' with label '{}'. Unlock the feature flag before deleting it.".format(feature_name, entry.label) exception_messages.append(exception) except ResourceModifiedError: exception = "Failed to delete feature '{}' with label '{}' due to a conflicting operation.".format(feature_name, entry.label) exception_messages.append(exception) except HttpResponseError as ex: exception_messages.append(str(ex)) raise CLIError('Delete operation failed. The following error(s) occurred:\n' + json.dumps(exception_messages, indent=2, ensure_ascii=False)) # Log errors if partially succeeded if exception_messages: if deleted_kvs: logger.error('Delete operation partially failed. The following error(s) occurred:\n%s\n', json.dumps(exception_messages, indent=2, ensure_ascii=False)) else: raise CLIError('Delete operation failed. \n' + json.dumps(exception_messages, indent=2, ensure_ascii=False)) # Convert result list of KeyValue to ist of FeatureFlag deleted_ff = [] for success_kv in deleted_kvs: success_ff = map_keyvalue_to_featureflag(success_kv, show_conditions=False) deleted_ff.append(success_ff) return deleted_ff
def _apm_migration_consent(cmd, new_workspace_resource_id, existing_workspace_resource_id): from azure.cli.command_modules.resource.custom import show_resource new_workspace = show_resource(cmd, [new_workspace_resource_id]) if _is_workspace_centric(new_workspace): if existing_workspace_resource_id: existing_workspace = show_resource(cmd, [existing_workspace_resource_id]) need_consent = _is_resource_centric(existing_workspace) else: # This is a classic AI which isn't binding to a log analytics workspace. need_consent = True if need_consent: from azure.cli.core.util import user_confirmation user_confirmation('Specified workspace is configured with workspace-based access mode and some APM features may be impacted. Consider selecting another workspace or allow resource-based access in the workspace settings. Please refer to https://aka.ms/apm-workspace-access-mode for details. Do you want to continue?')
def disable_feature(cmd, feature, name=None, label=None, connection_string=None, yes=False, auth_mode="key", endpoint=None): key = FeatureFlagConstants.FEATURE_FLAG_PREFIX + feature azconfig_client = get_appconfig_data_client(cmd, name, connection_string, auth_mode, endpoint) retry_times = 3 retry_interval = 1 for i in range(0, retry_times): try: retrieved_kv = azconfig_client.get_configuration_setting(key=key, label=label) except ResourceNotFoundError: raise CLIError("Feature flag '{}' with label '{}' not found.".format(feature, label)) except HttpResponseError as exception: raise CLIError("Failed to retrieve feature flags from config store. " + str(exception)) try: if retrieved_kv is None or retrieved_kv.content_type != FeatureFlagConstants.FEATURE_FLAG_CONTENT_TYPE: raise CLIError("The feature flag {} does not exist.".format(feature)) # we make sure that value retrieved is a valid json and only has the fields supported by backend. # if it's invalid, we catch appropriate exception that contains # detailed message feature_flag_value = map_keyvalue_to_featureflagvalue(retrieved_kv) feature_flag_value.enabled = False confirmation_message = "Are you sure you want to disable this feature '{}'?".format(feature) user_confirmation(confirmation_message, yes) updated_key_value = __update_existing_key_value(azconfig_client=azconfig_client, retrieved_kv=retrieved_kv, updated_value=json.dumps(feature_flag_value, default=lambda o: o.__dict__, ensure_ascii=False)) return map_keyvalue_to_featureflag(keyvalue=updated_key_value, show_conditions=False) except HttpResponseError as exception: if exception.status_code == StatusCodes.PRECONDITION_FAILED: logger.debug('Retrying feature disable operation %s times with exception: concurrent setting operations', i + 1) time.sleep(retry_interval) else: raise CLIError(str(exception)) except Exception as exception: raise CLIError(str(exception)) raise CLIError("Failed to disable the feature flag '{}' due to a conflicting operation.".format(feature))
def _create_vnet_subnet_delegation(cmd, nw_client, resource_client, delegation_service_name, resource_group, vnet_name, subnet_name, location, server_name, vnet_address_pref, subnet_address_pref, yes): VirtualNetwork, AddressSpace = cmd.get_models( 'VirtualNetwork', 'AddressSpace', resource_type=ResourceType.MGMT_NETWORK) if not check_existence(resource_client, vnet_name, resource_group, 'Microsoft.Network', 'virtualNetworks'): user_confirmation( "Do you want to create a new Vnet {0} in resource group {1}". format(vnet_name, resource_group), yes=yes) logger.warning('Creating new Vnet "%s" in resource group "%s"', vnet_name, resource_group) nw_client.virtual_networks.begin_create_or_update( resource_group, vnet_name, VirtualNetwork( name=vnet_name, location=location, address_space=AddressSpace( address_prefixes=[vnet_address_pref]))).result() else: logger.warning('Using existing Vnet "%s" in resource group "%s"', vnet_name, resource_group) # check if vnet prefix is in address space and add if not there vnet = nw_client.virtual_networks.get(resource_group, vnet_name) # validate whether vnet location is same as server validate_vnet_location(vnet, location) prefixes = vnet.address_space.address_prefixes subnet_exist = check_existence(resource_client, subnet_name, resource_group, 'Microsoft.Network', 'subnets', parent_name=vnet_name, parent_type='virtualNetworks') if not subnet_exist and vnet_address_pref not in prefixes: logger.warning( 'The address prefix does not exist in the Vnet. Adding address prefix %s to Vnet %s.', vnet_address_pref, vnet_name) vnet.address_space.address_prefixes += [vnet_address_pref] nw_client.virtual_networks.begin_create_or_update( resource_group, vnet_name, vnet).result() return _create_subnet_delegation(cmd, nw_client, resource_client, delegation_service_name, resource_group, vnet_name, subnet_name, location, server_name, subnet_address_pref, yes)
def delete_local_context(cmd, name=None, all=False, yes=False, purge=False, recursive=False): # pylint: disable=redefined-builtin if name: return cmd.cli_ctx.local_context.delete(name) if all: from azure.cli.core.util import user_confirmation if purge: user_confirmation('You are going to delete local context persistence file. ' 'Are you sure you want to continue this operation ?', yes) cmd.cli_ctx.local_context.delete_file(recursive) else: user_confirmation('You are going to clear all local context value. ' 'Are you sure you want to continue this operation ?', yes) cmd.cli_ctx.local_context.clear(recursive)
def delete_key(cmd, key, name=None, label=None, yes=False, connection_string=None, auth_mode="key", endpoint=None): azconfig_client = get_appconfig_data_client(cmd, name, connection_string, auth_mode, endpoint) # list_configuration_settings returns kv with null label when: # label = ASCII null 0x00, or URL encoded %00 # In delete, import and export commands, we treat missing --label as null label # In list, restore and revision commands, we treat missing --label as all labels entries = __read_kv_from_config_store(azconfig_client, key=key, label=label if label else SearchFilterOptions.EMPTY_LABEL) confirmation_message = "Found '{}' key-values matching the specified key and label. Are you sure you want to delete these key-values?".format(len(entries)) user_confirmation(confirmation_message, yes) deleted_entries = [] exception_messages = [] for entry in entries: try: deleted_kv = azconfig_client.delete_configuration_setting(key=entry.key, label=entry.label, etag=entry.etag, match_condition=MatchConditions.IfNotModified) deleted_entries.append(convert_configurationsetting_to_keyvalue(deleted_kv)) except ResourceReadOnlyError: exception = "Failed to delete read-only key-value with key '{}' and label '{}'. Unlock the key-value before deleting it.".format(entry.key, entry.label) exception_messages.append(exception) except ResourceModifiedError: exception = "Failed to delete key-value with key '{}' and label '{}' due to a conflicting operation.".format(entry.key, entry.label) exception_messages.append(exception) except HttpResponseError as ex: exception_messages.append(str(ex)) raise CLIError('Delete operation failed. The following error(s) occurred:\n' + json.dumps(exception_messages, indent=2, ensure_ascii=False)) # Log errors if partially succeeded if exception_messages: if deleted_entries: logger.error('Delete operation partially failed. The following error(s) occurred:\n%s\n', json.dumps(exception_messages, indent=2, ensure_ascii=False)) else: raise CLIError('Delete operation failed. \n' + json.dumps(exception_messages, indent=2, ensure_ascii=False)) return deleted_entries
def acr_repository_delete( cmd, registry_name, repository=None, image=None, resource_group_name=None, # pylint: disable=unused-argument tenant_suffix=None, username=None, password=None, yes=False): _validate_parameters(repository, image) if image: # If --image is specified, repository must be empty. repository, tag, manifest = _parse_image_name(image, allow_digest=True) else: # This is a request on repository tag, manifest = None, None login_server, username, password = get_access_credentials( cmd=cmd, registry_name=registry_name, tenant_suffix=tenant_suffix, username=username, password=password, repository=repository, permission=RepoAccessTokenPermission.DELETE_META_READ.value) if tag or manifest: manifest = _delete_manifest_confirmation(login_server=login_server, username=username, password=password, repository=repository, tag=tag, manifest=manifest, yes=yes) path = '/v2/{}/manifests/{}'.format(repository, manifest) else: user_confirmation( "Are you sure you want to delete the repository '{}' " "and all images under it?".format(repository), yes) path = _get_repository_path(repository) return request_data_from_registry(http_method='delete', login_server=login_server, path=path, username=username, password=password)[0]
def acr_connected_registry_deactivate(cmd, client, connected_registry_name, registry_name, yes=False, resource_group_name=None): _, resource_group_name = validate_managed_registry(cmd, registry_name, resource_group_name) user_confirmation( "Are you sure you want to deactivate the connected registry '{}' in '{}'?" .format(connected_registry_name, registry_name), yes) return client.begin_deactivate( resource_group_name=resource_group_name, registry_name=registry_name, connected_registry_name=connected_registry_name)
def firewall_rule_delete_func(client, resource_group_name, server_name, firewall_rule_name, yes=None): result = None if not yes: user_confirmation( "Are you sure you want to delete the firewall-rule '{0}' in server '{1}', resource group '{2}'" .format(firewall_rule_name, server_name, resource_group_name)) try: result = client.begin_delete(resource_group_name, server_name, firewall_rule_name) except Exception as ex: # pylint: disable=broad-except logger.error(ex) return result
def acr_manifest_delete(cmd, registry_name=None, manifest_spec=None, manifest_id=None, tenant_suffix=None, username=None, password=None, yes=False): if (manifest_id and manifest_spec) or (not manifest_id and not (registry_name and manifest_spec)): raise InvalidArgumentValueError(BAD_ARGS_ERROR_MANIFEST) if manifest_id: registry_name, repository, tag, manifest = _parse_fqdn( cmd, manifest_id[0]) else: repository, tag, manifest = _parse_image_name(manifest_spec, allow_digest=True) if not manifest: image = repository + ':' + tag repository, tag, manifest = get_image_digest(cmd, registry_name, image, tenant_suffix, username, password) login_server, username, password = get_access_credentials( cmd=cmd, registry_name=registry_name, tenant_suffix=tenant_suffix, username=username, password=password, repository=repository, permission=RepoAccessTokenPermission.DELETE.value) user_confirmation( "Are you sure you want to delete the artifact '{}'" " and all manifests that refer to it?".format(manifest), yes) return request_data_from_registry(http_method='delete', login_server=login_server, path=_get_v2_manifest_path( repository, manifest), username=username, password=password)[0]
def acr_connected_registry_deactivate(cmd, client, connected_registry_name, registry_name, yes=False, resource_group_name=None): _, resource_group_name = validate_managed_registry(cmd, registry_name, resource_group_name) subscription_id = get_subscription_id(cmd.cli_ctx) user_confirmation( "Are you sure you want to deactivate the connected registry '{}' in '{}'?" .format(connected_registry_name, registry_name), yes) return client.deactivate(subscription_id=subscription_id, resource_group_name=resource_group_name, registry_name=registry_name, connected_registry_name=connected_registry_name)
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 unlock_feature(cmd, feature, name=None, label=None, connection_string=None, yes=False, auth_mode="key", endpoint=None): key = FeatureFlagConstants.FEATURE_FLAG_PREFIX + feature azconfig_client = get_appconfig_data_client(cmd, name, connection_string, auth_mode, endpoint) retry_times = 3 retry_interval = 1 for i in range(0, retry_times): try: retrieved_kv = azconfig_client.get_configuration_setting(key=key, label=label) except ResourceNotFoundError: raise CLIError("Feature '{}' with label '{}' does not exist.".format(feature, label)) except HttpResponseError as exception: raise CLIError("Failed to retrieve feature flags from config store. " + str(exception)) if retrieved_kv is None or retrieved_kv.content_type != FeatureFlagConstants.FEATURE_FLAG_CONTENT_TYPE: raise CLIError("The feature '{}' you are trying to unlock does not exist.".format(feature)) confirmation_message = "Are you sure you want to unlock the feature '{}' with label '{}'".format(feature, label) user_confirmation(confirmation_message, yes) try: new_kv = azconfig_client.set_read_only(retrieved_kv, read_only=False, match_condition=MatchConditions.IfNotModified) return map_keyvalue_to_featureflag(convert_configurationsetting_to_keyvalue(new_kv), show_conditions=False) except HttpResponseError as exception: if exception.status_code == StatusCodes.PRECONDITION_FAILED: logger.debug('Retrying unlock operation %s times with exception: concurrent setting operations', i + 1) time.sleep(retry_interval) else: raise CLIError(str(exception)) except Exception as exception: raise CLIError(str(exception)) raise CLIError("Failed to unlock the feature '{}' with label '{}' due to a conflicting operation.".format(feature, label))
def confluent_organization_delete(client, resource_group_name, organization_name, no_wait=False, yes=None): if not yes: org = client.get(resource_group_name=resource_group_name, organization_name=organization_name) default_msg = '- This action cannot be undone.\n' \ f'- This will permanently delete \'{organization_name}\' and its Azure subscription.\n' \ '- Stop billing for the selected Confluent organization through Azure Marketplace.\n' \ 'Do you want to proceed' if org.offer_detail.plan_id in [ 'confluent-cloud-azure-payg-prod', 'confluent-cloud-azure-payg-stag' ]: user_confirmation(default_msg) else: user_confirmation( '- The action cannot be undone and will permanently delete this resource.\n' '- Resource deletion is a permanent action. All the resources, contract purchased ' 'and its Azure integration will be permanently deleted and will unsubscribe you ' 'from this service.\n' '- If you delete the resource, you will not be able to restore the commit contract ' 'and create Confluent cloud resource once again with this contract.\n' '- If you are deleting the Confluent cloud resource after 14 days into the contract ' 'term, you will not get a refund for this service.\n' '- The resource is also associated with other non-dependent resources like clusters' ', environments, topics etc. Such associated resources on Confluent cloud will be ' 'scheduled for deletion. For more information on the Confluent Cloud cluster ' 'deletion process and timeline, please contact Confluent Support: ' 'https://support.confluent.io/\n' 'Do you want to proceed') return sdk_no_wait(no_wait, client.begin_delete, resource_group_name=resource_group_name, organization_name=organization_name)