Go以AWS SDK aws-sdk-go-v2
來設定S3 bucket access point的policy。
範例環境:
- Go 1.19
事前要求
參考「AWS 建立IAM管理使用者及credentials」設定供應用程式存取AWS需要的IAM管理員credentials。
參考「Golang 建立AWS S3 bucket access point」建立S3 bucket access point。
設定S3 access point policy
呼叫s3contorl.Client.PutAccessPointPolicy
傳入s3control.PutAccessPointPolicyInput
設定access point的policy。
s3control.PutAccessPointPolicyInput
填入以下屬性:
AccountId
- 擁有bucket的AWS帳戶號碼。Name
- access point名稱。Policy
- access point的policy JSON。
main.go
package main
import (
"context"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/s3control"
)
func main() {
ctx := context.TODO()
client := NewS3ControlClient(ctx)
accountId := "423456789012"
apName := "ap-1" // access point name
policy := `{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowAllGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:ap-northeast-1:423456789012:accesspoint/ap-1/object/*"
}
]
}`
input := &s3control.PutAccessPointPolicyInput{
AccountId: &accountId,
Name: &apName,
Policy: &policy,
}
_, err := client.PutAccessPointPolicy(ctx, input)
if err != nil {
panic(err)
}
}
func NewS3ControlClient(ctx context.Context) *s3control.Client {
cfg, err := config.LoadDefaultConfig(
ctx,
config.WithRegion("ap-northeast-1"),
)
if err != nil {
panic(err)
}
return s3control.NewFromConfig(cfg) // Create an Amazon S3 Control client
}
測試
執行Go應用程式後在AWS console檢視設定的access point policy。
沒有留言:
張貼留言