All Products
Search
Document Center

Object Storage Service:Bucket policy (Python SDK V2)

Last Updated:Jul 31, 2025

A bucket policy is an OSS authorization policy that you can use to grant or restrict fine-grained access to specified OSS resources for identified users, such as Alibaba Cloud accounts, RAM users, RAM roles, or anonymous users. For example, you can grant read-only permissions on specified OSS resources to a RAM user that belongs to another Alibaba Cloud account.

Notes

  • Before you configure a bucket policy, ensure that you are familiar with this feature. For more information, see Bucket Policy.

  • The sample code in this topic uses the region ID cn-hangzhou for the China (Hangzhou) region as an example. By default, a public endpoint is used. If you want to access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For more information about the regions and endpoints that OSS supports, see Regions and endpoints.

  • You must have the oss:PutBucketPolicy permission to set a bucket policy, the oss:GetBucketPolicy permission to query a bucket policy, and the oss:DeleteBucketPolicy permission to delete a bucket policy. For more information, see Attach a custom policy to a RAM user.

Method definitions

Set a bucket policy

put_bucket_policy(request: PutBucketPolicyRequest, **kwargs) → PutBucketPolicyResult

Query a bucket policy

get_bucket_policy(request: GetBucketPolicyRequest, **kwargs) → GetBucketPolicyResult

Delete a bucket policy

delete_bucket_policy(request: DeleteBucketPolicyRequest, **kwargs) → DeleteBucketPolicyResult

Parameter

Type

Description

request

PutBucketPolicyRequest

The request parameters. For more information, see PutBucketPolicyRequest

GetBucketPolicyRequest

The request parameters. For more information, see GetBucketPolicyRequest

DeleteBucketPolicyRequest

The request parameters. For more information, see DeleteBucketPolicyRequest

Return values

Type

Description

PutBucketPolicyResult

The return value. For more information, see PutBucketPolicyResult

GetBucketPolicyResult

The return value. For more information, see GetBucketPolicyResult

DeleteBucketPolicyResult

The return value. For more information, see DeleteBucketPolicyResult

For the complete definition of the method to set a bucket policy, see put_bucket_policy.

For the complete definition of the method to query a bucket policy, see get_bucket_policy.

For the complete definition of the method to delete a bucket policy, see delete_bucket_policy.

Sample code

Set a bucket policy

You can use the following code to set a bucket policy.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line parameter parser to obtain command-line parameters.
parser = argparse.ArgumentParser(description="put bucket policy sample")
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse command-line parameters.
    args = parser.parse_args()

    # Load access credentials from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK.
    cfg = oss.config.load_default()
    # Set the credential provider.
    cfg.credentials_provider = credentials_provider
    # Set the region.
    cfg.region = args.region
    # If an endpoint is provided, set the endpoint in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSS client.
    client = oss.Client(cfg)

    # The following example shows how a resource owner (the owner of a bucket whose UID is 174649585760xxxx) uses a bucket policy to grant a specified user (a RAM user whose UID is 20214760404935xxxx) the permissions to list all objects in examplebucket.
    policy_text = "{\"Statement\": [{\"Effect\": \"Allow\", \"Action\": [\"oss:GetObject\", \"oss:ListObjects\"], \"Principal\": [\"20214760404935xxxx\"], \"Resource\": [\"acs:oss:*:174649585760xxxx:examplebucket/*\"]}], \"Version\": \"1\"}"

    # Apply the policy to the specified bucket.
    result = client.put_bucket_policy(oss.PutBucketPolicyRequest(
            bucket=args.bucket,
            body=policy_text,
    ))

    # Print the status code and request ID of the result.
    print(f'status code: {result.status_code}, request id: {result.request_id}')

if __name__ == "__main__":
    main()

Query a bucket policy

You can use the following code to query a bucket policy.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line parameter parser.
parser = argparse.ArgumentParser(description="get bucket policy sample")
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse command-line parameters.
    args = parser.parse_args()

    # Load access credentials from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK.
    cfg = oss.config.load_default()
    # Set the credential provider to the provider that obtains credentials from environment variables.
    cfg.credentials_provider = credentials_provider
    # Set the region.
    cfg.region = args.region
    # If an endpoint is provided, set the endpoint in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSS client.
    client = oss.Client(cfg)

    # Call the get_bucket_policy method to obtain the policy of the specified bucket.
    result = client.get_bucket_policy(oss.GetBucketPolicyRequest(
            bucket=args.bucket,
    ))

    # Print the returned status code, request ID, and response body.
    print(f'status code: {result.status_code},'
            f' request id: {result.request_id},'
            f' body: {result.body},'
    )

# Call the main function when the script is run as the main program.
if __name__ == "__main__":
    main()

Delete a bucket policy

You can use the following code to delete a bucket policy.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line parameter parser.
parser = argparse.ArgumentParser(description="delete bucket policy sample")
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse command-line parameters.
    args = parser.parse_args()

    # Load access credentials from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK.
    cfg = oss.config.load_default()
    # Set the credential provider to the provider that obtains credentials from environment variables.
    cfg.credentials_provider = credentials_provider
    # Set the region.
    cfg.region = args.region
    # If an endpoint is specified, set the endpoint in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSS client.
    client = oss.Client(cfg)

    # Call the method to delete the bucket policy.
    result = client.delete_bucket_policy(oss.DeleteBucketPolicyRequest(
            bucket=args.bucket,  # Specify the name of the bucket on which the operation is performed.
    ))

    # Print the status code and request ID of the request result.
    print(f'status code: {result.status_code}, request id: {result.request_id}')

# Execute the main function when the script is run as the main program.
if __name__ == "__main__":
    main()

References