Manage bucket policies using OSS SDK for Python 2.0

更新时间:
复制 MD 格式

Bucket policies let you authorize or restrict access to specific OSS resources for anonymous users or identified users such as Alibaba Cloud accounts, RAM users, and RAM roles. For example, you can grant a RAM user of another Alibaba Cloud account read-only permissions on specific OSS resources.

Notes

  • Before you configure bucket policies, make sure that you understand this feature.

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

  • The oss:PutBucketPolicy permission is required to configure a bucket policy. The oss:GetBucketPolicy permission is required to query a bucket policy. The oss:DeleteBucketPolicy permission is required to delete a bucket policy. For more information, see Grant a custom policy.

Methods

Configure a bucket policy

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

Query bucket policies

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 for the PutBucketPolicy operation. For request parameters, see PutBucketPolicyRequest.

GetBucketPolicyRequest

The request for the GetBucketPolicy operation. For request parameters, see GetBucketPolicyRequest.

DeleteBucketPolicyRequest

The request for the DeleteBucketPolicy operation. For request parameters, see DeleteBucketPolicyRequest.

Response parameters

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 method definition for configuring a bucket policy, see put_bucket_policy.

For the complete method definition for querying bucket policies, see get_bucket_policy.

For the complete method definition for deleting a bucket policy, see delete_bucket_policy.

Sample code

Configure a bucket policy

The following sample code configures a bucket policy.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line parameter parser for obtaining the values of the 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 the command-line parameters.
    args = parser.parse_args()

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

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

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

    # In the following example, the bucket owner whose UID is 174649585760xxxx uses a bucket policy to authorize a RAM user whose UID is 20214760404935xxxx 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,
    ))

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

if __name__ == "__main__":
    main()

Query bucket policies

The following sample code queries bucket policies.

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 the command-line parameters.
    args = parser.parse_args()

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

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

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

    # Call get_bucket_policy to query the bucket policies.
    result = client.get_bucket_policy(oss.GetBucketPolicyRequest(
            bucket=args.bucket,
    ))

    # Display the HTTP 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 directly run.
if __name__ == "__main__":
    main()

Delete a bucket policy

The following sample code deletes 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 configuration of the SDK.
    cfg = oss.config.load_default()
    # Set the credential provider.
    cfg.credentials_provider = credentials_provider
    # Specify the region.
    cfg.region = args.region
    # If an endpoint is provided from the command line, update the endpoint in the configuration with the provided endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

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

    # Call the delete_bucket_policy method.
    result = client.delete_bucket_policy(oss.DeleteBucketPolicyRequest(
            bucket=args.bucket,  # Specify the name of the bucket to perform the operation on.
    ))

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

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

References