If you no longer use an Object Storage Service (OSS) bucket, you can delete the bucket to stop unnecessary charges.
Deleted buckets cannot be recovered. Make sure that the data in the buckets is no longer needed before you delete the buckets. If you want to continue using the data in the buckets, back up the data in advance. For more information, see Back up buckets.
Prerequisites
All objects in the bucket are deleted. You can manually delete objects from a bucket or have objects automatically deleted from a bucket based on a lifecycle rule.
If the bucket contains a small number of objects, we recommend that you manually delete them. For more information, see Delete objects.
To delete a large number of objects, we recommend that you configure lifecycle rules to delete the objects. For more information, see Configure lifecycle rules.
ImportantTo delete a versioning-enabled bucket, make sure that all current and previous versions of objects in the bucket are deleted. For more information, see Configure versioning.
Parts generated by multipart upload or resumable upload tasks in the bucket are deleted. For more information, see Delete parts.
All LiveChannels in the bucket are deleted. For more information, see DeleteLiveChannel.
Use the OSS console
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
In the left-side navigation tree, click Delete Bucket. On the Delete Bucket page, click Delete Bucket and follow the on-screen instructions to complete the delete operation.
Use ossbrowser
You can use ossbrowser to perform the same bucket-level operations that you can perform in the OSS console. You can follow the on-screen instructions in ossbrowser to delete a bucket. For more information about how to use ossbrowser, see Use ossbrowser.
Use OSS SDKs
The following sample code provides examples on how to delete a bucket by using OSS SDKs for common programming languages. For more information about how to delete a bucket by using OSS SDKs for other programming languages, see Overview.
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
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";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
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();
}
}
}
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\OssClient;
use OSS\Core\OssException;
// Obtain access credentials from environment variables. Before you run the sample code, make sure that you specified the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
$accessKeyId = getenv("OSS_ACCESS_KEY_ID");
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the bucket. Example: examplebucket.
$bucket= "examplebucket";
try{
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
$ossClient->deleteBucket($bucket);
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
const OSS = require('ali-oss');
const client = new OSS({
// 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 oss-cn-hangzhou.
region: 'yourregion',
// Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET
});
async function deleteBucket() {
try {
// Specify the name of the bucket.
const result = await client.deleteBucket('yourbucketname');
console.log(result);
} catch (err) {
console.log(err);
}
}
deleteBucket();
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# 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.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
# Specify the name of the bucket. Example: examplebucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
try:
# Delete the bucket.
bucket.delete_bucket()
except oss2.exceptions.BucketNotEmpty:
print('bucket is not empty.')
except oss2.exceptions.NoSuchBucket:
print('bucket does not exist')
using Aliyun.OSS;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// 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.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket.
var bucketName = "examplebucket";
// Delete the bucket.
public void DeleteBucket(string bucketName)
{
try
{
client.DeleteBucket(bucketName);
Console.WriteLine("Delete bucket succeeded");
}
catch (Exception ex)
{
Console.WriteLine("Delete bucket failed. {0}", ex.Message);
}
}
DeleteBucketRequest deleteBucketRequest = new DeleteBucketRequest("bucketName");
// Delete the bucket asynchronously.
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) {
// Handle request exceptions.
if (clientException != null) {
// Handle client exceptions, such as network exceptions.
clientException.printStackTrace();
}
if (serviceException != null) {
// Handle service exceptions.
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
}
}
});
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
/// 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.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the name of the bucket. Example: examplebucket.
// Delete the bucket.
err = client.DeleteBucket("examplebucket")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
}
OSSDeleteBucketRequest * delete = [OSSDeleteBucketRequest new];
// Specify the name of the bucket. 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;
}];
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize information about the account that is used to access OSS. */
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
/* 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. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
/* 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 resources, such as network resources. */
ShutdownSdk();
return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Use a char* string to initialize data of the aos_string_t type. */
aos_str_set(&options->config->endpoint, endpoint);
/* 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. */
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"));
/* Specify whether to use CNAME to access OSS. A value of 0 indicates that CNAME is not used. */
options->config->is_cname = 0;
/* Configure 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 resources and memory resources. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* Create a memory pool to manage memory. aos_pool_t is equivalent to apr_pool_t. The code used to create a memory pool is included in the APR library. */
aos_pool_t *pool;
/* Create a memory pool. The value of the second parameter is NULL. This value indicates that the pool does not inherit other memory pools. */
aos_pool_create(&pool, NULL);
/* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
oss_request_options_t *oss_client_options;
/* Allocate the memory resources in the memory pool to the options. */
oss_client_options = oss_request_options_create(pool);
/* Initialize 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 char* data to a bucket of the aos_string_t type. */
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 operation releases the memory resources allocated for the request. */
aos_pool_destroy(pool);
/* Release the allocated global resources. */
aos_http_io_deinitialize();
return 0;
}
require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
# In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
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.
access_key_id: ENV['OSS_ACCESS_KEY_ID'],
access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the name of the bucket. Example: examplebucket.
client.delete_bucket('examplebucket')
Use ossutil
You can use ossutil to delete a bucket. For more information, see Delete buckets.
Use RESTful APIs
If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see DeleteBucket.
FAQ
What do I do if I fail to delete a bucket?
The bucket cannot be deleted if the bucket is not empty, or if you do not have the permissions to delete the bucket. Troubleshoot the issue based on the following causes:
The bucket is not empty.
Delete all objects, parts, and LiveChannels from the bucket.
You do not have the permissions to delete the bucket.
The bucket is empty, but you are not authorized to delete the bucket as a RAM user. Obtain the required permissions to delete the bucket:
If your RAM policy does not include the
oss:DeleteBucket
permission, you cannot delete the bucket as a RAM user. In this case, you need to ask a RAM user who has the administrator permissions to add theoss:DeleteBucket
permission to your RAM policy.If the
oss:DeleteBucket
permission is included in your RAM policy, but the Deny statement is configured for theoss:DeleteBucket
permission in the bucket policy, the bucket cannot be deleted. In this case, you need to change Deny to Allow or delete the bucket policy. Then, you can delete the bucket.
How do I delete a bucket for which OSS-HDFS is enabled?
You can delete a bucket for which OSS-HDFS is enabled only in the OSS console. Delete all objects in the bucket before you delete the bucket.
Buckets and objects cannot be restored after they are deleted. Exercise caution when you perform this operation.
For example, you want to delete a non-empty bucket named examplebucket in the China (Hangzhou) region for which OSS-HDFS is enabled.
Delete all objects in the examplebucket bucket.
Use the OSS console
In the left-side navigation pane of the OSS console, click Buckets. On the Buckets page, click the name of the bucket.
In the left-side navigation tree, choose Object Management > Objects.
In the left-side navigation tree, click Object Management. On the Objects page, delete all objects on the OSS Object tab and the HDFS tab.
NoteYou can delete multiple objects on the OSS Object tab at a time. For more information, see Use the OSS console.
You cannot delete multiple objects on the HDFS tab at a time. You can manually delete all objects one by one on the HDFS tab.
Run HDFS shell commands
hdfs dfs -rm -r -skipTrash oss://examplebucket.cn-hangzhou.oss-dls.aliyuncs.com/*
For more information, see Connect non-EMR clusters to OSS-HDFS.
Run Jindo CLI commands
jindo fs -rm oss://examplebucket.cn-shanghai.oss-dls.aliyuncs.com/*
For more information, see Use Jindo CLI commands to access OSS or OSS-HDFS.
Delete the examplebucket bucket.
How do I create a bucket that has the same name as the deleted bucket?
You can create a bucket that has the same name as the deleted bucket approximately 30 minutes after the deletion.