Se você não precisar mais de um bucket, exclua-o para interromper todas as cobranças. Como as taxas do Object Storage Service (OSS) são geradas pelos recursos dentro de um bucket, limpe todos os recursos antes da exclusão. Excluir o bucket é a forma mais segura de evitar cobranças inesperadas causadas por recursos faturáveis esquecidos. Os dados não podem ser recuperados após a exclusão do bucket e outro usuário pode reivindicar o nome dele assim que for liberado. Para parar completamente de usar o OSS, exclua todos os buckets da sua conta.
Avalie os riscos antes da exclusão
-
Risco de perda irreversível de dados
Esta ação é irreversível e remove permanentemente todos os objetos, suas versões anteriores e partes. Faça backup dos seus dados antecipadamente.
-
Risco de interrupção de serviço
A exclusão de um bucket interrompe imediatamente quaisquer sites, aplicativos ou serviços de CDN dependentes. Certifique-se de que nenhum serviço esteja acessando ativamente o bucket.
-
Risco de apropriação indevida do nome do bucket
Após a exclusão de um bucket, seu nome entra em um período de espera de 4 a 8 horas antes de ser liberado. Caso precise reservar o nome, recomendamos esvaziar o bucket em vez de excluí-lo.
-
Risco de exclusão síncrona
Se você ativou a replicação entre regiões ou a replicação na mesma região, a operação de exclusão também pode limpar os dados do bucket de destino. Verifique sua configuração.
-
Estimativa de custo e tempo
Limpar muitos objetos pode gerar taxas de solicitação de API e levar várias horas ou mais, dependendo do volume de dados.
Verifique os recursos que devem ser excluídos
Ao tentar excluir um bucket contendo recursos como objetos, partes, pontos de acesso, aceleradores ou URLs de ingestão RTMP, o sistema reporta o erro "The bucket is not empty". Recomendamos usar o assistente de exclusão no console do OSS, que verifica e lista automaticamente todos os itens pendentes de limpeza.
Faça login no console do OSS.
No painel de navegação à esquerda, clique em Buckets. Na página exibida, clique no nome do bucket desejado.
No painel de navegação à esquerda, role até a parte inferior e clique em Delete Bucket.
-
Na página Delete Bucket, clique em Delete Bucket. Em seguida, visualize os itens pendentes de limpeza.

Limpe os recursos necessários
Para excluir um bucket, primeiro limpe todos os seus recursos. Remova os recursos identificados pelo sistema. Se o bucket contiver muitos objetos, recomendamos usar uma regra de ciclo de vida para automatizar a limpeza.
Objetos
Se a coluna de status do recurso objetos indicar que o recurso HDFS está ativado, limpe primeiro os objetos HDFS. Caso o versionamento esteja habilitado, a página Objects exibirá tanto a versão atual quanto todas as anteriores. Portanto, selecionar e excluir todos os objetos removerá todas as versões.
Objetos do OSS
Console do OSS
Na página Delete Bucket, na área Cleanup Tasks, localize o recurso de objetos e clique em Delete.
Selecione todos os objetos e clique em Permanently Delete na parte inferior da página.
Na caixa de diálogo exibida, clique em OK.
ossutil
Exclui todos os objetos do bucket, incluindo as versões atuais e anteriores.
ossutil rm oss://examplebucket/ -r
Para mais exemplos, consulte rm (delete).
Objetos HDFS
Console do OSS
Na coluna Status do recurso Objects, clique em Pause Now para interromper a tarefa em segundo plano do HDFS.
Clique em Delete para acessar a aba HDFS.
Clique em Permanently Delete para cada objeto até excluir todos os objetos HDFS.
Comandos shell do HDFS
hdfs dfs -rm -r -skipTrash oss://examplebucket.cn-hangzhou.oss-dls.aliyuncs.com/*
Para obter mais informações, consulte Executar operações comuns para o serviço OSS-HDFS usando comandos shell do HDFS.
Partes
Console do OSS
Na página Delete Bucket, na área Delete Task, localize o item de recurso Parts e clique em Delete.
Na página Objects, clique em Part Management.
No painel Parts, clique em Delete All.
Na caixa de diálogo exibida, clique em OK.
ossutil
Exclui todas as partes de uploads multipart incompletos ou cancelados.
ossutil rm oss://examplebucket -m -r -f
Para obter mais informações, consulte rm (delete).
Pontos de acesso
Na página Delete Bucket, na área Delete Task, localize o item de recurso Access Point e clique em Delete.
Para cada ponto de acesso, clique em Delete Access Point.
Siga as instruções na tela para excluir a política de acesso correspondente.
Após excluir a política de acesso, retorne à lista de pontos de acesso. Insira o nome do ponto de acesso conforme solicitado e clique em OK para concluir a exclusão.
Aceleradores
A exclusão de um acelerador remove apenas seus dados em cache. Os dados armazenados no bucket do OSS não são afetados.
Na página Delete Bucket, na seção Delete Task, localize o item de recurso Accelerator e clique em Delete.
Na lista de aceleradores do OSS, na coluna Actions, clique em Delete.
-
Insira o nome do acelerador conforme solicitado e clique em OK para concluir a exclusão.

URLs de ingestão RTMP
Não é possível visualizar ou excluir os LiveChannels de um bucket pelo console do OSS ou ferramentas. Execute essas operações usando um SDK ou chamando a API. Para obter mais informações, consulte DeleteLiveChannel. O código de exemplo a seguir mostra como excluir um LiveChannel específico.
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.LiveChannelGenericRequest;
/**
* This code provides an example of how to delete a specified LiveChannel.
* This program demonstrates how to delete a LiveChannel in Alibaba Cloud OSS.
*/
public class Demo {
public static void main(String[] args) throws Exception {
// The OSS endpoint. Select an endpoint based on your region. This example uses the endpoint for the China (Hangzhou) region.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the bucket name. For example, examplebucket.
String bucketName = "examplebucket";
// Specify the LiveChannel name.
String liveChannelName = "yourLiveChannelName";
// Specify the region where the bucket is located. For example, set Region to cn-hangzhou for China (Hangzhou).
String region = "cn-hangzhou";
// Create an OSSClient instance.
// When the OSSClient instance is no longer needed, call the shutdown method to release resources.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Create a request to delete the LiveChannel.
LiveChannelGenericRequest request = new LiveChannelGenericRequest(bucketName, liveChannelName);
// Execute the delete operation.
ossClient.deleteLiveChannel(request);
} catch (OSSException oe) {
// Handle exceptions returned by the OSS server.
oe.printStackTrace();
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (Exception e) {
System.out.println("Caught an unexpected exception:");
e.printStackTrace();
} finally {
if (ossClient != null) {
// Release OSSClient resources.
ossClient.shutdown();
}
}
}
}
Objetos
Se a coluna de status do recurso objetos indicar que o recurso HDFS está ativado, limpe primeiro os objetos HDFS. Caso o versionamento esteja habilitado, a página Objects exibirá tanto a versão atual quanto todas as anteriores. Portanto, selecionar e excluir todos os objetos removerá todas as versões.
Objetos do OSS
Console do OSS
Na página Delete Bucket, clique em Delete Bucket, localize o recurso objects e clique em Delete.
Selecione todos os objetos e clique em Permanently Delete na parte inferior da página.
Na caixa de diálogo exibida, clique em OK.
ossutil
Exclui todos os objetos do bucket, incluindo as versões atuais e anteriores.
ossutil rm oss://examplebucket/ -r
Para mais exemplos, consulte rm (delete).
Objetos HDFS
Console do OSS
Na coluna Status do recurso object, clique em Pause Now para interromper a tarefa em segundo plano do HDFS.
Clique em Delete para acessar a aba HDFS.
Clique sequencialmente em Permanently Delete até excluir todos os arquivos HDFS.
Comandos shell do HDFS
hdfs dfs -rm -r -skipTrash oss://examplebucket.cn-hangzhou.oss-dls.aliyuncs.com/*
Para obter mais informações, consulte Executar operações comuns para o serviço OSS-HDFS usando comandos shell do HDFS.
Partes
Partes são fragmentos de objetos gerados por uploads multipart incompletos.
Console do OSS
Na página Delete Bucket, clique em Delete Bucket, localize o item de recurso Parts e clique em Delete.
Na página Objects, clique em Part Management.
No painel Parts, clique em Delete All.
Na caixa de diálogo, clique em OK.
ossutil
Exclui todas as partes de uploads multipart incompletos ou cancelados.
ossutil rm oss://examplebucket -m -r -f
Para obter mais informações, consulte rm (delete).
Pontos de acesso
Na barra de navegação à esquerda, clique em Access Point.
Para cada ponto de acesso, clique em Delete Access Point.
Siga as instruções na tela para excluir a política de acesso correspondente.
Após excluir a política de acesso, retorne à lista de pontos de acesso. Insira o nome do ponto de acesso conforme solicitado e clique em OK para concluir a exclusão.
Aceleradores
A exclusão de um acelerador remove apenas seus dados em cache. Os dados armazenados no bucket do OSS não são afetados.
Na barra de navegação à esquerda, clique em Bucket Settings > Accelerator.
Na lista de aceleradores do OSS, clique em Delete na coluna Actions.
-
Insira o nome do acelerador conforme solicitado na página e clique em OK para concluir a exclusão.

URLs de ingestão RTMP
Não é possível visualizar ou excluir os LiveChannels de um bucket pelo console do OSS ou ferramentas. Use um SDK ou chame a API. Para obter mais informações, consulte a documentação da API DeleteLiveChannel. O código de exemplo a seguir mostra como excluir um LiveChannel específico.
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.LiveChannelGenericRequest;
/**
* This code provides an example of how to delete a specified LiveChannel.
* This program demonstrates how to delete a LiveChannel in Alibaba Cloud OSS.
*/
public class Demo {
public static void main(String[] args) throws Exception {
// The OSS endpoint. Select an endpoint based on your region. This example uses the endpoint for the China (Hangzhou) region.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the bucket name. For example, examplebucket.
String bucketName = "examplebucket";
// Specify the LiveChannel name.
String liveChannelName = "yourLiveChannelName";
// Specify the region where the bucket is located. For example, set Region to cn-hangzhou for China (Hangzhou).
String region = "cn-hangzhou";
// Create an OSSClient instance.
// When the OSSClient instance is no longer needed, call the shutdown method to release resources.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Create a request to delete the LiveChannel.
LiveChannelGenericRequest request = new LiveChannelGenericRequest(bucketName, liveChannelName);
// Execute the delete operation.
ossClient.deleteLiveChannel(request);
} catch (OSSException oe) {
// Handle exceptions returned by the OSS server.
oe.printStackTrace();
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (Exception e) {
System.out.println("Caught an unexpected exception:");
e.printStackTrace();
} finally {
if (ossClient != null) {
// Release OSSClient resources.
ossClient.shutdown();
}
}
}
}
Excluir o bucket
Após confirmar que todos os recursos no bucket foram limpos, exclua o bucket.
Console do OSS
Retorne à página Delete Bucket do bucket desejado.
Clique em Delete Bucket, insira o nome do bucket conforme solicitado e clique em OK para concluir a exclusão.
ossutil
O comando a seguir exclui o bucket chamado examplebucket.
ossutil api delete-bucket --bucket examplebucket
Para obter mais informações, consulte delete-bucket.
OSS SDK
As seções a seguir fornecem exemplos de código para excluir um bucket usando SDKs comuns. Para informações sobre outros SDKs, consulte Visão geral do SDK.
Java
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release associated resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Delete the bucket.
ossClient.deleteBucket(bucketName);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
Python
import argparse
import alibabacloud_oss_v2 as oss
# Create a command-line argument parser and describe that this script is used to delete a specified OSS bucket.
parser = argparse.ArgumentParser(description="Delete a specified OSS bucket.")
# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket to delete.', required=True)
# Add the --endpoint command-line argument, which specifies the domain name that other services can use to access OSS. This argument is not required.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS.')
def main():
"""
The main function, which is used to parse command-line arguments and delete the specified bucket.
"""
args = parser.parse_args() # Parse command-line arguments.
# Load credentials from environment variables for identity verification.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Use the default configurations of the SDK and set the credential provider and region.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = args.region
# If the endpoint parameter is provided, set the endpoint in the configuration.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Create an OSS client based on the configurations.
client = oss.Client(cfg)
# Construct a request to delete the specified bucket.
request = oss.DeleteBucketRequest(bucket=args.bucket)
try:
# Send the request and obtain the response.
result = client.delete_bucket(request)
# Print the status code and request ID of the response.
print(f'status code: {result.status_code},'
f' request id: {result.request_id}')
except oss.exceptions.OperationError as e:
# Catch and print possible exceptions.
print(f"Failed to delete bucket: {e}")
if __name__ == "__main__":
main() # The script entry point. The main function is called when the file is run.
Go
package main
import (
"context"
"flag"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
var (
region string
bucketName string
)
func init() {
// Define command line parameters to specify the region and name of the bucket.
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}
func main() {
// Parse command line parameters.
flag.Parse()
// Check whether the name of the bucket is specified.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is specified.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request object for deletion.
request := &oss.DeleteBucketRequest{
Bucket: oss.Ptr(bucketName),
}
// Call the DeleteBucket method.
result, err := client.DeleteBucket(context.TODO(), request)
if err != nil {
log.Fatalf("failed to delete bucket %v", err)
}
// Display the result.
log.Printf("delete bucket result:%#v\n", result)
}
PHP
<?php
require_once __DIR__ . '/../vendor/autoload.php'; // Automatically load objects and dependency libraries.
use AlibabaCloud\Oss\V2 as Oss;
// Specify command line parameters.
$optsdesc = [
"region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located. Example: oss-cn-hangzhou.
"endpoint" => ['help' => The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
"bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
];
$longopts = \array_map(function ($key) {
return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));
// Parse the command line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Specifies that the required parameters are not configured.
exit(1);
}
}
// Obtain the values of the command line parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Use environment variables to load the credential information (AccessKey ID and AccessKey secret).
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations of the SDK.
$cfg=Oss\Config::loadDefault(); // Load the default configurations of the SDK.
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided.
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Create a request to delete the bucket.
$request = new Oss\Models\DeleteBucketRequest($bucket);
// Use the deleteBucket method to delete the bucket.
$result = $client->deleteBucket($request);
// Display the returned result.
printf(
'status code:' . $result-> statusCode. PHP_EOL . // The HTTP response status code.
'request id:' . $result->requestId // The unique identifier of the request.
);
Node.js
const OSS = require('ali-oss');
const client = new OSS({
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
region: 'yourregion',
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Set bucket to the name of your bucket.
bucket: 'yourBucketName',
});
async function deleteBucket() {
try {
// Specify the bucket name.
const result = await client.deleteBucket('yourbucketname');
console.log(result);
} catch (err) {
console.log(err);
}
}
deleteBucket();
.NET
using System;
using Aliyun.OSS;
using Aliyun.OSS.Common;
namespace Samples
{
public class Program
{
public static void Main(string[] args)
{
// Set endpoint to the Endpoint of the region where your bucket is located. For example, if your bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Set bucketName to the name of your bucket. Example: examplebucket.
var bucketName = "examplebucket314";
// Set region to the ID of the region where your bucket is located. For example, if your bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Set the signature version to V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
client.DeleteBucket(bucketName);
Console.WriteLine("Delete bucket succeeded");
}
catch (Exception ex)
{
Console.WriteLine("Delete bucket failed. {0}", ex.Message);
}
}
}
}
Android
DeleteBucketRequest deleteBucketRequest = new DeleteBucketRequest("bucketName");
// Asynchronously delete the bucket.
OSSAsyncTask deleteBucketTask = oss.asyncDeleteBucket(deleteBucketRequest, new OSSCompletedCallback<DeleteBucketRequest, DeleteBucketResult>() {
@Override
public void onSuccess(DeleteBucketRequest request, DeleteBucketResult result) {
Log.d("asyncDeleteBucket", "Success!");
}
@Override
public void onFailure(DeleteBucketRequest request, ClientException clientException, ServiceException serviceException) {
// The request failed.
if (clientException != null) {
// Client exceptions, such as network exceptions.
clientException.printStackTrace();
}
if (serviceException != null) {
// Service exceptions.
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
}
}
});
iOS
OSSDeleteBucketRequest * delete = [OSSDeleteBucketRequest new];
// Specify the bucket name. For example, examplebucket.
delete.bucketName = @"examplebucket";
OSSTask * deleteTask = [client deleteBucket:delete];
[deleteTask continueWithBlock:^id(OSSTask *task) {
if (!task.error) {
NSLog(@"delete bucket success!");
} else {
NSLog(@"delete bucket failed, error: %@", task.error);
}
return nil;
}];
// Block the current thread until the task is complete.
// [getdeleteTask waitUntilFinished];
C++
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/*Initialize the OSS account information.*/
/*Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.*/
std::string Endpoint = "yourEndpoint";
/*Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.*/
std::string Region = "yourRegion";
/*Specify the bucket name, for example, examplebucket.*/
std::string BucketName = "examplebucket";
/*Initialize network resources.*/
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/*Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.*/
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/*Delete the bucket.*/
DeleteBucketRequest request(BucketName);
auto outcome = client.DeleteBucket(request);
if (outcome.isSuccess()) {
std::cout << "Delete bucket successfully." << std::endl;
} else {
std::cout << "Failed to delete bucket. Error code: " << outcome.error().Code()
<< ", Message: " << outcome.error().Message()
<< ", RequestId: " << outcome.error().RequestId() << std::endl;
}
/*Release network resources.*/
ShutdownSdk();
return 0;
}
C
#include "oss_api.h"
#include "aos_http_io.h"
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Set the bucket name. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Use a char* string to initialize the aos_string_t type. */
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Before running this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
// Configure the following two additional parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specify whether to use a CNAME to access OSS. A value of 0 indicates that a CNAME is not used. */
options->config->is_cname = 0;
/* Set network parameters, such as the timeout period. */
options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
/* Call the aos_http_io_initialize method in main() to initialize global resources, such as network and memory resources. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* A memory pool (pool) for memory management, equivalent to apr_pool_t. Its implementation code is in the APR library. */
aos_pool_t *pool;
/* Create a new memory pool. The second parameter is NULL, which indicates that the pool does not inherit from other memory pools. */
aos_pool_create(&pool, NULL);
/* Create and initialize options. This parameter includes global configuration information, such as the endpoint, access_key_id, access_key_secret, is_cname, and curl. */
oss_request_options_t *oss_client_options;
/* Allocate memory for options in the memory pool. */
oss_client_options = oss_request_options_create(pool);
/* Initialize the client options oss_client_options. */
init_options(oss_client_options);
/* Initialize the parameters. */
aos_string_t bucket;
aos_table_t *resp_headers = NULL;
aos_status_t *resp_status = NULL;
/* Assign the char* data to the aos_string_t bucket. */
aos_str_set(&bucket, bucket_name);
/* Delete the bucket. */
resp_status = oss_delete_bucket (oss_client_options, &bucket, &resp_headers);
if (aos_status_is_ok(resp_status)) {
printf("delete bucket succeeded\n");
} else {
printf("delete bucket failed\n");
}
/* Release the memory pool. This releases the memory allocated for resources during the request. */
aos_pool_destroy(pool);
/* Release the previously allocated global resources. */
aos_http_io_deinitialize();
return 0;
}
Ruby
require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
# The China (Hangzhou) region is used as an example. Specify the actual Endpoint for your region.
endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
# Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
access_key_id: ENV['OSS_ACCESS_KEY_ID'],
access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the bucket name. For example, examplebucket.
client.delete_bucket('examplebucket')
Limpeza automatizada para grandes volumes
Se um bucket contiver um número massivo de objetos (milhões ou mais), configurar uma regra de ciclo de vida é o método de limpeza mais eficiente e econômico. Essa abordagem define uma regra de "expirar e excluir" que instrui o sistema a excluir automaticamente todos os dados no bucket após um período especificado. Se você não estiver familiarizado com regras de ciclo de vida, recomendamos testá-las primeiro em um bucket fora de produção.
Nota: A exclusão de objetos é uma ação irreversível. Proceda com cautela.
Versionamento desativado
Para um bucket com versionamento desativado, configure apenas uma única regra de ciclo de vida para limpar automática e rapidamente todos os objetos e partes (partes não mescladas de uploads multipart).
Faça login no console do OSS, acesse a página Buckets e clique no nome do bucket desejado.
-
No painel de navegação à esquerda, escolha e confirme se o versionamento está desativado para o bucket.

-
No painel de navegação à esquerda, escolha Data Management > Lifecycle. Configure uma regra de ciclo de vida para excluir automaticamente todos os objetos no bucket 1 dia após a última modificação e limpar automaticamente as partes criadas há mais de 1 dia.

Versionamento ativado
Quando o versionamento está ativado para um bucket, ele pode conter versões atuais de objetos, versões anteriores, partes e marcadores de exclusão. Configure apenas uma única regra de ciclo de vida para limpar automática e rapidamente todos esses itens.
Faça login no console do OSS, acesse a página Buckets e clique no nome do bucket desejado.
-
Na barra de navegação à esquerda, selecione e confirme se o versionamento está ativado para o bucket.

-
Na barra de navegação à esquerda, selecione e configure uma regra de ciclo de vida para excluir automaticamente todos os objetos das versões atuais e anteriores no bucket 1 dia após a última modificação e limpar automaticamente as partes criadas há mais de 1 dia. Esta regra também limpa marcadores de exclusão.

Perguntas frequentes
Erro "Bucket not empty"
Este erro indica que o bucket ainda contém recursos. Recomendamos usar o console do OSS para identificar e limpar os recursos restantes conforme descrito em Limpar os recursos necessários. Em seguida, tente excluir o bucket novamente.
Recriar um bucket com o mesmo nome
Após a exclusão de um bucket, seu nome entra em um período de espera de 4 a 8 horas. Durante esse tempo, nenhum usuário pode criar um novo bucket com esse nome. Se você precisar de um bucket imediatamente, use um novo nome.
Após o término do período de espera, o nome fica disponível para todos os usuários. Se você não recriar o bucket prontamente, outro usuário poderá reivindicar o nome antes de você.
Exclusão em lote de vários buckets
A exclusão em lote é uma operação de alto risco que pode causar perda permanente de dados. Antes de prosseguir, verifique cuidadosamente a lista de buckets a serem excluídos e garanta que todos os dados necessários tenham backup.
O console do OSS não oferece suporte à exclusão em lote. No entanto, você pode escrever um script que use ossutil para executar essa operação.
A lógica principal é a seguinte:
Prepare uma lista: Crie um arquivo de texto ou lista precisa contendo os nomes de todos os buckets que você deseja excluir.
-
Execute em loop: Seu script deve iterar por essa lista e executar as duas etapas principais a seguir para cada nome de bucket.
Esvazie o bucket: Para o bucket atual, chame o comando ossutil para esvaziá-lo.
Exclua o bucket vazio: Após confirmar que a etapa anterior foi bem-sucedida, chame o comando ossutil para excluir o bucket.
Erro "Insufficient permissions"
Antes de excluir um bucket, limpe todos os recursos dentro dele. Esse processo requer múltiplas permissões, como permissões de listagem e exclusão. Para evitar falhas na exclusão devido à falta de permissões, recomendamos entrar em contato com um administrador para conceder a permissão AliyunOSSFullAccess à sua identidade RAM.
Como interromper a cobrança do OSS
Para interromper todas as cobranças do Object Storage Service (OSS), você deve excluir todos os buckets da sua conta. Você ainda pode incorrer em cobranças enquanto qualquer bucket existir, mesmo que vazio, ou se tiver contas pendentes.
Recuperar um bucket excluído
Não. A exclusão de um bucket é uma operação irreversível. Sempre faça backup dos seus dados antes de excluir um bucket.