Delete a bucket (Python SDK V1)

Updated at:

Delete a bucket when you no longer need it or want to stop accruing storage charges. OSS charges are based on resources stored inside a bucket. Deleting the bucket ensures you don't miss any billable resources and incur unexpected fees. To stop using OSS entirely, delete all buckets under your account.

Warning

Deletion is permanent and irreversible. Before proceeding:

  • Back up your data. Objects in a deleted bucket cannot be recovered. If you still need the data, back it up first. See Back up a bucket.

  • Be aware of the naming risk. After deletion, the bucket name is released and becomes available to other users, who could then receive requests intended for your former bucket. To keep the bucket name, empty the bucket's contents instead of deleting it.

Prerequisites

Before you begin, make sure that:

  • The bucket is empty. OSS does not allow deleting a non-empty bucket. Clear all required resources first.

  • You have the `oss:DeleteBucket` permission. By default, an Alibaba Cloud account has full permissions. RAM users and RAM roles have no permissions by default — grant the permission using a RAM policy or bucket policy.

Usage notes

  • Endpoint: The examples use the public endpoint for the China (Hangzhou) region (https://oss-cn-hangzhou.aliyuncs.com). For access from other Alibaba Cloud services in the same region, use an internal endpoint instead. See Regions and endpoints.

  • Access credentials: The examples read credentials from environment variables (OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET). See Configure access credentials using OSS SDK for Python 1.0.

  • OSSClient initialization: The examples create an OSSClient instance using an OSS endpoint. To use a custom domain or Security Token Service (STS), see Initialization.

Delete a bucket

The following example deletes a bucket. If the bucket still contains objects or the bucket does not exist, the SDK raises an exception.

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Read credentials from environment variables.
# Set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET before running this example.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Set the endpoint for the region where your bucket is located.
# Example: https://oss-cn-hangzhou.aliyuncs.com for China (Hangzhou).
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Specify the region that matches the endpoint. Required for V4 signatures.
region = "cn-hangzhou"

# Replace yourBucketName with the name of the bucket to delete.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

try:
    bucket.delete_bucket()
except oss2.exceptions.BucketNotEmpty:
    print('bucket is not empty.')
except oss2.exceptions.NoSuchBucket:
    print('bucket does not exist')

What's next