This topic was translated by AI and is currently in queue for revision by our editors. Alibaba Cloud does not guarantee the accuracy of AI-translated content. Request expedited revision

Delete buckets to stop billing

Updated at: 2025-02-28 19:44
important

This topic contains important information on necessary precautions. We recommend that you read this topic carefully before proceeding.

To stop billing for a bucket, you must delete it. To cease OSS service billing and effectively shut down the service, delete all buckets under the current account.

Warning
  • Once a bucket is deleted, its name becomes available and may be claimed by others. To retain the bucket name, consider emptying the bucket instead of deleting it.

  • Data within a deleted bucket cannot be restored. Ensure you no longer need the data before deleting the bucket, or back it up beforehand. For more information about backups, see Backup Buckets.

Resources to clean up before deleting a bucket

Before deleting a bucket, ensure all resources are cleaned up. While most users only store files in their buckets, some may use advanced features that require additional configuration items to be addressed. The OSS console can automatically detect resources needing cleanup, and it is recommended to use the OSS console for this process.

Methods

Use the OSS console

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  3. In the left-side navigation pane, click Delete Bucket.

  4. On the Delete Bucket page, follow the instructions to complete the resource cleanup, and then click Delete Immediately.

    screenshot_2025-02-27_11-39-13

Use the command line tool ossutil

The command line tool ossutil can be used to delete a bucket. For information on installing ossutil, see Install Ossutil.

Use the following command to delete the bucket named examplebucket:

ossutil api delete-bucket --bucket examplebucket

For more details on this command, see Delete Bucket.

Use Alibaba Cloud SDK

Below are code examples for deleting a bucket using common SDKs. For other SDKs, see SDK Overview.

Java
PHP
Node.js
Python
.NET
Android
IOS
C++
C
Ruby
Go
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";
        // 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. 
        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();
            }
        }
    }
} 
<?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\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;

// 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 = new 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. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the bucket. Example: examplebucket. 
$bucket= "examplebucket";

try{
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

    $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,
  authorizationV4: true,
  // Specify the name of your bucket.
  bucket: 'yourBucketName',
});

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.ProviderAuthV4(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.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

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 System;
using Aliyun.OSS;
using Aliyun.OSS.Common;


namespace Samples
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // 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 = "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. 
            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 = "examplebucket314";
            // 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.
            const string region = "cn-hangzhou";
            // Create a ClientConfiguration instance and modify parameters as required.
            var conf = new ClientConfiguration();
            // Use the signature algorithm 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);
            }
        }
    }
}
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) {
        // 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());
        }
    }
});
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;
}];
// Implement synchronous blocking to wait for the task to complete. 
// [getdeleteTask waitUntilFinished];
#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 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. */
    std::string Region = "yourRegion";
    
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize resources, such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* 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);
    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 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";
/* 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. */
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 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 two additional parameters.
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    /* 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')
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(&region, "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)
}

Related API

The methods described above are based on API operations. For highly customized program requirements, you can directly call REST API operations, which include signature calculations. For more details, see DeleteBucket.

Permission description

By default, an Alibaba Cloud account has full permissions. RAM users or RAM roles under an Alibaba Cloud account have no permissions by default and must be granted permissions through RAM Policy or Bucket Policy.

API

Action

Description

API

Action

Description

DeleteBucket

oss:DeleteBucket

Delete a bucket.

Billing description

Deleting a bucket may incur certain billable items. For detailed pricing information, see or OSS Pricing.

API

Billable items

Description

API

Billable items

Description

DeleteBucket

PUT requests

You are charged request fees based on the number of successful requests.

Limits

FAQ

How to delete a bucket for which OSS-HDFS is enabled?

To delete a bucket with OSS-HDFS enabled, you must use the OSS console and ensure all data within the bucket is removed first.

Warning

Be cautious when deleting buckets and objects as they cannot be restored once removed.

For example, to delete a non-empty bucket named examplebucket in the China (Hangzhou) region with OSS-HDFS enabled, follow these steps:

  1. Remove all data from examplebucket.

    1. Delete all objects on the HDFS tab.

      Use the OSS console
      Use HDFS shell commands
      Use Jindo CLI commands
      1. Click Buckets, and then select the bucket where OSS-HDFS is enabled.

      2. In the left-side navigation tree, choose Object Management > Objects.

      3. Delete all files under the HDFS tab.

        Note

        Files on the HDFS tab do not support batch deletion. You can manually delete files on the HDFS tab individually.

      hdfs dfs -rm -r -skipTrash oss://examplebucket.cn-hangzhou.oss-dls.aliyuncs.com/*

      For more details, see Perform Common Operations in OSS-HDFS Quick Start Using HDFS Shell Commands.

      jindo fs -rm oss://examplebucket.cn-shanghai.oss-dls.aliyuncs.com/*

      For more details, see Access Using Jindo CLI.

    2. Delete all objects on the OSS Object tab.

      Use the OSS console
      Use the command line tool ossutil
      1. Click Buckets, and then select the bucket where OSS-HDFS is enabled.

      2. In the left-side navigation tree, choose Object Management > Objects.

      3. Select all files on the OSS Object tab, and then click Permanently Delete.

      ossutil rm oss://examplebucket --all-versions -r
  2. Delete examplebucket.

How do i create a bucket that has the same name as a deleted bucket?

You can create a bucket with the same name as a deleted bucket approximately 4 to 8 hours after deletion. Once deleted, the bucket name is available for anyone to claim.

  • On this page (1)
  • Resources to clean up before deleting a bucket
  • Methods
  • Use the OSS console
  • Use the command line tool ossutil
  • Use Alibaba Cloud SDK
  • Related API
  • Permission description
  • Billing description
  • Limits
  • FAQ
  • How to delete a bucket for which OSS-HDFS is enabled?
  • How do i create a bucket that has the same name as a deleted bucket?
Feedback
phone Contact Us