All Products
Search
Document Center

Object Storage Service:Bucket policy (Python SDK V2)

Last Updated:Feb 27, 2026

A bucket policy grants or restricts fine-grained access to specific OSS resources for identified users, including Alibaba Cloud accounts, RAM users, RAM roles, and anonymous users. For example, a bucket policy can grant read-only permissions on specific objects to a RAM user from a different Alibaba Cloud account.

Prerequisites

Before you begin, ensure that you have:

  • Familiarity with the bucket policy feature. For more information, see Bucket Policy

  • The required permissions: For more information, see Attach a custom policy to a RAM user.

    PermissionOperation
    oss:PutBucketPolicySet a bucket policy
    oss:GetBucketPolicyQuery a bucket policy
    oss:DeleteBucketPolicyDelete a bucket policy

Client initialization

All examples on this page use the same client initialization. Set your credentials as environment variables and create the client once:

import argparse
import json
import alibabacloud_oss_v2 as oss

parser = argparse.ArgumentParser(description="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 endpoint that other services can use to access OSS.')

args = parser.parse_args()

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

cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = args.region
if args.endpoint is not None:
    cfg.endpoint = args.endpoint

client = oss.Client(cfg)
The sample code uses the region ID cn-hangzhou for the China (Hangzhou) region. By default, a public endpoint is used. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For more information, see Regions and endpoints.

Set a bucket policy

Call put_bucket_policy to attach a JSON policy to a bucket.

Method signature

put_bucket_policy(request: PutBucketPolicyRequest, **kwargs) -> PutBucketPolicyResult
ParameterTypeDescription
requestPutBucketPolicyRequestRequest parameters. Key fields: bucket (bucket name) and body (JSON policy string).

Return value: PutBucketPolicyResult. Contains status_code and request_id.

For the complete method definition, see put_bucket_policy.

Grant read access to a specific RAM user

The following example grants a RAM user (UID: 20214760404935xxxx) permissions to get and list objects in a bucket owned by Alibaba Cloud account 174649585760xxxx:

# Define the policy as a Python dict for readability.
policy = {
    "Version": "1",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "oss:GetObject",
                "oss:ListObjects"
            ],
            "Principal": [
                "20214760404935xxxx"
            ],
            "Resource": [
                "acs:oss:*:174649585760xxxx:examplebucket/*"
            ]
        }
    ]
}

result = client.put_bucket_policy(oss.PutBucketPolicyRequest(
    bucket=args.bucket,
    body=json.dumps(policy),
))

print(f'status code: {result.status_code}, request id: {result.request_id}')

Grant public read access to a prefix

The following example grants anonymous users permission to read objects under a specific prefix:

This example uses "Principal": ["*"] to grant anonymous access. Before you run this example, disable Block Public Access on the target bucket. New buckets have Block Public Access enabled by default. If Block Public Access is enabled, the API returns 403 AccessDenied. For more information, see Block Public Access.
policy = {
    "Version": "1",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "oss:GetObject"
            ],
            "Principal": [
                "*"
            ],
            "Resource": [
                "acs:oss:*:174649585760xxxx:examplebucket/public/*"
            ]
        }
    ]
}

result = client.put_bucket_policy(oss.PutBucketPolicyRequest(
    bucket=args.bucket,
    body=json.dumps(policy),
))

print(f'status code: {result.status_code}, request id: {result.request_id}')

Query a bucket policy

Call get_bucket_policy to retrieve the JSON policy attached to a bucket.

Method signature

get_bucket_policy(request: GetBucketPolicyRequest, **kwargs) -> GetBucketPolicyResult
ParameterTypeDescription
requestGetBucketPolicyRequestRequest parameters. Key field: bucket (bucket name).

Return value: GetBucketPolicyResult. Contains status_code, request_id, and body (the policy JSON string).

For the complete method definition, see get_bucket_policy.

Retrieve and display the current policy

result = client.get_bucket_policy(oss.GetBucketPolicyRequest(
    bucket=args.bucket,
))

print(f'status code: {result.status_code}')
print(f'request id: {result.request_id}')
print(f'policy: {result.body}')

Delete a bucket policy

Call delete_bucket_policy to remove all policy statements from a bucket.

Method signature

delete_bucket_policy(request: DeleteBucketPolicyRequest, **kwargs) -> DeleteBucketPolicyResult
ParameterTypeDescription
requestDeleteBucketPolicyRequestRequest parameters. Key field: bucket (bucket name).

Return value: DeleteBucketPolicyResult. Contains status_code and request_id.

For the complete method definition, see delete_bucket_policy.

Remove all policy statements

result = client.delete_bucket_policy(oss.DeleteBucketPolicyRequest(
    bucket=args.bucket,
))

print(f'status code: {result.status_code}, request id: {result.request_id}')

References