All Products
Search
Document Center

Object Storage Service:Bucket policy (Go SDK V2)

Last Updated:Aug 02, 2025

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

Notes

  • Before you configure a bucket policy, make sure 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. 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 products in the same region, use an internal Endpoint. For more information about the regions and Endpoints supported by OSS, see OSS regions and endpoints.

  • In this topic, access credentials are read from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • To set a bucket policy, you must have the oss:PutBucketPolicy permission. To retrieve a bucket policy, you must have the oss:GetBucketPolicy permission. To delete a bucket policy, you must have the oss:DeleteBucketPolicy permission. For more information, see Grant custom policies to RAM users.

Sample code

Set a bucket policy

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

package main

import (
	"context"
	"flag"
	"log"
	"strings"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // The region.
	bucketName string // The bucket name.
)

// The init function is used to initialize command-line parameters.
func init() {
	flag.StringVar(&region, "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 bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and set the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Define the bucket policy.
	policy := `{
		"Version": "1",
		"Statement": [
			{
				"Action": [
					"oss:PutObject",
					"oss:GetObject"
				],
				"Effect": "Deny",
				"Principal": ["1234567890"],
				"Resource": ["acs:oss:*:1234567890:*/*"]
			}
		]
	}`

	// Create a request to set the bucket policy.
	request := &oss.PutBucketPolicyRequest{
		Bucket: oss.Ptr(bucketName),       // The bucket name.
		Body:   strings.NewReader(policy), // The bucket policy.
	}

	// Execute the operation to set the bucket policy.
	result, err := client.PutBucketPolicy(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put bucket policy %v", err)
	}

	// Print the result of setting the bucket policy.
	log.Printf("put bucket policy result:%#v\n", result)
}

Get a bucket policy

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

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"
)

// Define global variables.
var (
	region     string // The region.
	bucketName string // The bucket name.
)

// The init function is used to initialize command-line parameters.
func init() {
	flag.StringVar(&region, "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 bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and set the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to get the bucket policy.
	request := &oss.GetBucketPolicyRequest{
		Bucket: oss.Ptr(bucketName),
	}

	// Execute the operation to get the bucket policy.
	result, err := client.GetBucketPolicy(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket policy %v", err)
	}

	// Print the result of getting the bucket policy.
	log.Printf("get bucket policy result:%#v\n", result)
}

Delete a bucket policy

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

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"
)

// Define global variables.
var (
	region     string // The region.
	bucketName string // The bucket name.
)

// The init function is used to initialize command-line parameters.
func init() {
	flag.StringVar(&region, "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 bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and set the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to delete the bucket policy.
	request := &oss.DeleteBucketPolicyRequest{
		Bucket: oss.Ptr(bucketName),
	}

	// Execute the operation to delete the bucket policy.
	result, err := client.DeleteBucketPolicy(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete bucket policy %v", err)
	}

	// Print the result of deleting the bucket policy.
	log.Printf("delete bucket policy result:%#v\n", result)
}

References

  • For the complete sample code for setting a bucket policy, see GitHub example.

  • For the API operation for setting a bucket policy, see PutBucketPolicy.

  • For the complete sample code for retrieving a bucket policy, see GitHub example.

  • For the API operation for retrieving a bucket policy, see GetBucketPolicy.

  • For the complete sample code for deleting a bucket policy, see GitHub example.

  • For the API operation for deleting a bucket policy, see DeleteBucketPolicy.