Jika Anda tidak lagi memerlukan bucket, Anda dapat menghapusnya untuk menghentikan semua penagihan. Karena biaya Object Storage Service (OSS) dikenakan untuk resource di dalam bucket, Anda harus membersihkan semua resource tersebut sebelum menghapus bucket. Menghapus bucket merupakan cara paling andal untuk mencegah biaya tak terduga akibat resource berbayar yang terlewatkan. Perhatikan bahwa data tidak dapat dipulihkan setelah bucket dihapus, dan pengguna lain dapat mengklaim nama tersebut setelah dilepas. Untuk sepenuhnya berhenti menggunakan OSS, Anda harus menghapus semua bucket dalam akun Anda.
Nilai risiko sebelum penghapusan
Risiko kehilangan data permanen
Tindakan ini tidak dapat dikembalikan dan akan menghapus secara permanen semua objek, versi sebelumnya, serta bagian-bagiannya. Backup data Anda terlebih dahulu.
Risiko gangguan layanan
Menghapus bucket langsung mengganggu situs web, aplikasi, atau layanan CDN apa pun yang bergantung padanya. Pastikan tidak ada layanan yang sedang mengakses bucket tersebut.
Risiko squatting nama bucket
Setelah bucket dihapus, namanya memasuki periode tenang selama 4 hingga 8 jam sebelum dilepas. Jika Anda perlu menyimpan nama tersebut, kami menyarankan mengosongkan bucket alih-alih menghapusnya.
Risiko penghapusan sinkron
Jika Anda telah mengaktifkan cross-region replication atau replikasi wilayah yang sama, operasi penghapusan juga dapat menghapus data dari bucket tujuan. Periksa konfigurasi Anda.
Perkiraan biaya dan waktu
Pembersihan banyak objek dapat menimbulkan biaya permintaan API dan memakan waktu beberapa jam atau lebih, tergantung pada volume data.
Periksa resource yang harus dihapus
Jika Anda mencoba menghapus bucket yang berisi resource seperti objects, parts, access points, accelerators, atau RTMP ingest URLs, sistem akan menampilkan error "The bucket is not empty". Kami menyarankan menggunakan wizard penghapusan di Konsol OSS, yang secara otomatis memindai dan mencantumkan semua item yang perlu dibersihkan.
-
Masuk ke Konsol OSS.
-
Di panel navigasi kiri, klik Buckets. Pada halaman yang muncul, klik nama bucket target.
Di panel navigasi kiri, gulir ke bawah dan klik Delete Bucket.
Pada halaman Delete Bucket, klik Delete Bucket. Anda kemudian dapat melihat item-item yang harus dibersihkan.

Bersihkan resource yang diperlukan
Untuk menghapus bucket, Anda harus terlebih dahulu membersihkan semua resource-nya. Bersihkan resource yang diidentifikasi oleh sistem. Jika bucket berisi banyak objek, kami menyarankan menggunakan aturan siklus hidup untuk mengotomatiskan pembersihan.
Objects
Jika kolom status untuk resource objects menunjukkan bahwa fitur HDFS diaktifkan, Anda harus membersihkan objek HDFS terlebih dahulu. Jika versioning diaktifkan, halaman Objects menampilkan versi saat ini dan semua versi sebelumnya. Oleh karena itu, memilih semua objek dan menghapusnya akan menghapus semua versi.
OSS objects
OSS console
Pada halaman Delete Bucket, klik Delete Bucket, temukan resource objects, lalu klik Delete.
Pilih semua objek dan klik Permanently Delete di bagian bawah halaman.
Pada kotak dialog yang muncul, klik OK.
ossutil
Menghapus semua objek dari bucket, termasuk versi saat ini dan sebelumnya.
ossutil rm oss://examplebucket/ -rUntuk contoh lainnya, lihat rm (delete).
HDFS objects
OSS console
Di kolom Status resource object, klik Pause Now untuk menghentikan tugas latar belakang HDFS.
Klik Delete untuk membuka tab HDFS.
Klik Permanently Delete secara berurutan hingga semua file HDFS dihapus.
HDFS shell commands
hdfs dfs -rm -r -skipTrash oss://examplebucket.cn-hangzhou.oss-dls.aliyuncs.com/*Untuk informasi lebih lanjut, lihat Lakukan operasi umum untuk layanan OSS-HDFS menggunakan perintah shell HDFS.
Parts
Parts adalah fragmen objek yang dihasilkan dari unggah multi-bagian yang belum lengkap.
OSS console
Pada halaman Delete Bucket, klik Delete Bucket, temukan item resource Parts, lalu klik Delete.
Pada halaman Objects, klik Part Management.
Di panel Parts, klik Delete All.
Pada kotak dialog, klik OK.
ossutil
Menghapus semua bagian dari unggah multi-bagian yang belum lengkap atau dibatalkan.
ossutil rm oss://examplebucket -m -r -fUntuk informasi lebih lanjut, lihat rm (delete).
Access points
Di bilah navigasi kiri, klik Access Point.
Untuk setiap access point, klik Delete Access Point.
Ikuti petunjuk di layar untuk menghapus kebijakan akses yang sesuai.
Setelah Anda menghapus kebijakan akses, kembali ke daftar access point. Masukkan nama access point seperti diminta, lalu klik OK untuk menyelesaikan penghapusan.
Accelerators
Perhatikan bahwa menghapus accelerator hanya menghapus data cache-nya. Data yang disimpan di bucket OSS tidak terpengaruh.
Di bilah navigasi kiri, klik Bucket Settings > Accelerator.
Di daftar accelerator OSS, klik Delete di kolom Actions.
Masukkan nama accelerator seperti diminta di halaman, lalu klik OK untuk menyelesaikan penghapusan.

RTMP ingest URLs
Anda tidak dapat melihat atau menghapus LiveChannels bucket melalui Konsol OSS atau alat lainnya. Sebagai gantinya, gunakan SDK atau panggil API. Untuk informasi lebih lanjut, lihat dokumentasi API DeleteLiveChannel. Contoh kode berikut menunjukkan cara menghapus LiveChannel tertentu.
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();
}
}
}
}Hapus bucket
Setelah Anda memastikan bahwa semua resource di dalam bucket telah dibersihkan, Anda dapat menghapus bucket tersebut.
OSS console
Kembali ke halaman Delete Bucket untuk bucket target.
Klik Delete Bucket, masukkan nama bucket seperti diminta, lalu klik OK untuk menyelesaikan penghapusan.
ossutil
Perintah berikut menghapus bucket bernama examplebucket.
ossutil api delete-bucket --bucket examplebucketUntuk informasi lebih lanjut, lihat delete-bucket.
OSS SDK
Bagian berikut menyediakan contoh kode untuk menghapus bucket menggunakan SDK umum. Untuk informasi tentang SDK lainnya, lihat Ikhtisar 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.OssError 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'; // Memuat objek dan pustaka dependensi secara otomatis.
use AlibabaCloud\Oss\V2 as Oss;
// Tentukan parameter baris perintah.
$optsdesc = [
"region" => ['help' => 'Wilayah tempat bucket berada.', 'required' => True], // (Required) Tentukan wilayah tempat bucket berada. Contoh: oss-cn-hangzhou.
"endpoint" => ['help' => 'Nama domain yang dapat digunakan layanan lain untuk mengakses OSS.', 'required' => False], // (Optional) Tentukan titik akhir yang dapat digunakan layanan lain untuk mengakses OSS.
"bucket" => ['help' => 'Nama bucket', 'required' => True], // (Required) Tentukan nama bucket.
];
$longopts = \array_map(function ($key) {
return "$key:"; // Tambahkan tanda titik dua (:) di akhir setiap parameter untuk menunjukkan bahwa nilai diperlukan.
}, array_keys($optsdesc));
// Uraikan parameter baris perintah.
$options = getopt("", $longopts);
// Periksa apakah parameter yang diperlukan telah dikonfigurasi.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Menentukan bahwa parameter yang diperlukan belum dikonfigurasi.
exit(1);
}
}
// Dapatkan nilai parameter baris perintah.
$region = $options["region"]; // Wilayah tempat bucket berada.
$bucket = $options["bucket"]; // Nama bucket.
// Gunakan variabel lingkungan untuk memuat informasi kredensial (ID AccessKey dan Rahasia AccessKey).
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Gunakan konfigurasi default SDK.
$cfg=Oss\Config::loadDefault(); // Memuat konfigurasi default SDK.
$cfg->setCredentialsProvider($credentialsProvider); // Tentukan penyedia kredensial.
$cfg->setRegion($region); // Tentukan wilayah.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Tentukan titik akhir jika titik akhir disediakan.
}
// Buat instans OSSClient.
$client = new Oss\Client($cfg);
// Buat permintaan untuk menghapus bucket.
$request = new Oss\Models\DeleteBucketRequest($bucket);
// Gunakan metode deleteBucket untuk menghapus bucket.
$result = $client->deleteBucket($request);
// Tampilkan hasil yang dikembalikan.
printf(
'status code:' . $result-> statusCode. PHP_EOL . // Kode status tanggapan HTTP.
'request id:' . $result->requestId // Pengidentifikasi unik dari permintaan.
);
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')Pembersihan otomatis untuk volume besar
Jika bucket berisi jumlah objek yang sangat besar (jutaan atau lebih), mengonfigurasi aturan siklus hidup merupakan metode pembersihan paling efisien dan hemat biaya. Pendekatan ini melibatkan pengaturan aturan "kedaluwarsa dan hapus" yang menginstruksikan sistem untuk secara otomatis menghapus semua data di dalam bucket setelah periode tertentu. Jika Anda belum familiar dengan aturan siklus hidup, kami menyarankan mengujinya terlebih dahulu di bucket non-produksi.
Catatan: Penghapusan objek merupakan tindakan yang tidak dapat dikembalikan. Lakukan dengan hati-hati.
Versioning dinonaktifkan
Untuk bucket dengan versioning dinonaktifkan, Anda hanya perlu mengonfigurasi satu aturan siklus hidup untuk secara otomatis dan cepat membersihkan semua objek dan parts (bagian yang belum digabung dari unggah multi-bagian).
Masuk ke Konsol OSS, buka halaman Buckets, lalu klik nama bucket target.
Di panel navigasi kiri, pilih dan pastikan versioning dinonaktifkan untuk bucket tersebut.

Di panel navigasi kiri, pilih Data Management > Lifecycle. Konfigurasikan aturan siklus hidup untuk secara otomatis menghapus semua objek di dalam bucket 1 hari setelah terakhir dimodifikasi, dan secara otomatis membersihkan parts yang dibuat lebih dari 1 hari lalu.

Versioning diaktifkan
Saat versioning diaktifkan untuk bucket, bucket tersebut dapat berisi versi objek saat ini, versi objek sebelumnya, parts, dan penanda hapus. Anda hanya perlu mengonfigurasi satu aturan siklus hidup untuk secara otomatis dan cepat membersihkan semua item tersebut.
Masuk ke Konsol OSS, buka halaman Buckets, lalu klik nama bucket target.
Di bilah navigasi kiri, pilih , dan pastikan versioning diaktifkan untuk bucket tersebut.

Di bilah navigasi kiri, pilih , dan konfigurasikan aturan siklus hidup untuk secara otomatis menghapus semua objek versi saat ini dan sebelumnya di dalam bucket 1 hari setelah modifikasi terakhir, serta secara otomatis membersihkan parts yang dibuat lebih dari 1 hari lalu. Aturan ini juga membersihkan penanda hapus.

FAQ
Error "Bucket not empty"
Error ini menunjukkan bucket masih berisi resource. Kami menyarankan menggunakan Konsol OSS untuk mengidentifikasi dan membersihkan resource yang tersisa seperti dijelaskan dalam Bersihkan resource yang diperlukan. Kemudian, coba hapus bucket lagi.
Membuat ulang bucket dengan nama yang sama
Setelah bucket dihapus, namanya memasuki periode tenang selama 4 hingga 8 jam. Selama periode ini, tidak ada pengguna yang dapat membuat bucket baru dengan nama tersebut. Jika Anda memerlukan bucket segera, gunakan nama baru.
Setelah periode tenang berakhir, nama tersebut tersedia untuk semua pengguna. Jika Anda tidak segera membuat ulang bucket, pengguna lain dapat mengklaim nama tersebut sebelum Anda sempat melakukannya.
Penghapusan batch beberapa bucket
Penghapusan batch merupakan operasi berisiko tinggi yang dapat menyebabkan kehilangan data permanen. Sebelum melanjutkan, verifikasi dengan cermat daftar bucket yang akan dihapus dan pastikan semua data penting telah dibackup.
Konsol OSS tidak mendukung penghapusan batch. Namun, Anda dapat menulis skrip yang menggunakan ossutil untuk melakukan operasi ini.
Logika intinya adalah sebagai berikut:
Siapkan daftar: Buat file teks atau daftar akurat yang berisi nama semua bucket yang ingin Anda hapus.
Eksekusi dalam loop: Skrip Anda harus mengulangi daftar ini dan melakukan dua langkah utama berikut untuk setiap nama bucket.
Kosongkan bucket: Untuk bucket saat ini, panggil perintah ossutil untuk mengosongkannya.
Hapus bucket kosong: Setelah memastikan langkah sebelumnya berhasil, panggil perintah ossutil untuk menghapus bucket tersebut.
Error "Insufficient permissions"
Sebelum menghapus bucket, Anda harus membersihkan semua resource di dalamnya. Proses ini memerlukan beberapa izin, seperti izin list dan delete. Untuk mencegah kegagalan penghapusan akibat izin yang kurang, kami menyarankan menghubungi administrator untuk memberikan izin AliyunOSSFullAccess kepada identitas RAM Anda.
Cara menghentikan penagihan OSS
Untuk menghentikan semua biaya Object Storage Service (OSS), Anda harus menghapus semua bucket dalam akun Anda. Anda mungkin tetap dikenai biaya selama masih ada bucket yang tersisa, meskipun kosong, atau jika Anda memiliki tagihan yang belum diselesaikan.
Memulihkan bucket yang dihapus
Tidak. Menghapus bucket merupakan operasi yang tidak dapat dikembalikan. Selalu backup data Anda sebelum menghapus bucket.