AdSense

網頁

2023/5/2

Golang 設定AWS S3 bucket policy

Go以AWS SDK aws-sdk-go-v2來設定S3 bucket policy。


範例環境:

  • Go 1.19


事前要求

參考「AWS 建立IAM管理使用者及credentials」設定供應用程式存取AWS需要的IAM管理員credentials。

參考「Golang 建立AWS S3 bucket」建立S3 bucket。


設定S3 bucket policy

呼叫s3.Client.PutBucketPolicy()傳入s3.PutBucketPolicyInput上傳bucket policy。

s3.PutBucketPolicyInput.Bucket填入bucket名稱。

s3.PutBucketPolicyInput.Policy填入JSON格式字串的policy,注意第一個字必須為{

main.go

package main

import (
    "context"

    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/service/s3"
)

func main() {
    ctx := context.TODO()

    client := NewS3Client(ctx)

    policy := `{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "DenyAllGetObject",
            "Effect": "Deny",
            "Principal": {
                "AWS": "*"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::aws-s3-bucket-202305021730/*"
        }
    ]
}
`
    bucket := "aws-s3-bucket-202305021730" // bucket name
    input := &s3.PutBucketPolicyInput{
        Bucket: &bucket,
        Policy: &policy,
    }
    _, err := client.PutBucketPolicy(ctx, input)
    if err != nil {
        panic(err)
    }
}

func NewS3Client(ctx context.Context) *s3.Client {
    cfg, err := config.LoadDefaultConfig(
        ctx,
        config.WithRegion("ap-northeast-1"),
    )
    if err != nil {
        panic(err)
    }
    return s3.NewFromConfig(cfg) // Create an Amazon S3 service client
}

github



測試

執行Go應用程式後在AWS console檢視上傳的bucket policy。




更新S3 bucket policy

更新bucket policy的方法相同,新的policy內容會覆蓋舊的。

例如下面把policy的Principal由原本的"AWS"改為"Service"。

main.go

package main

import (
    "context"

    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/service/s3"
)

func main() {
    ctx := context.TODO()

    client := NewS3Client(ctx)

    policy := `{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "DenyAllGetObject",
            "Effect": "Deny",
            "Principal": {
                "Service": [
                    "ecs.amazonaws.com"
                ]
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::aws-s3-bucket-202305021730/*"
        }
    ]
}
`
    bucket := "aws-s3-bucket-202305021730" // bucket name
    input := &s3.PutBucketPolicyInput{
        Bucket: &bucket,
        Policy: &policy,
    }
    _, err := client.PutBucketPolicy(ctx, input)
    if err != nil {
        panic(err)
    }
}

func NewS3Client(ctx context.Context) *s3.Client {
    cfg, err := config.LoadDefaultConfig(
        ctx,
        config.WithRegion("ap-northeast-1"),
    )
    if err != nil {
        panic(err)
    }
    return s3.NewFromConfig(cfg) // Create an Amazon S3 service client
}

測試

執行Go應用程式後在AWS console檢視更新的bucket policy。




沒有留言:

AdSense