AdSense

網頁

2024/5/22

Golang 設定GCP IAM Service Account為可存取Cloud Storage Bucket的Policy Principle

Go以Google Cloud Client Libraries for Go將IAM Service Account設定為Cloud Storage Bucket的Policy Principle。


事前要求

參考「Golang 建立GCP Service Account」建立Service Account。


設定

呼叫storage.NewClient建立storage.Client

呼叫storage.Client.Bucket取得操作bucket的物件storage.BucketHandle

呼叫storage.BucketHandle.IAM取得控制bucket存取的iam.Handle,接著呼叫iam.Handle.Policy取得bucket的iam.Policy

呼叫Policy.Add加入Service Account與Role的綁定,參數如下:

  • 第一個參數為member,即為要綁定的Serivice Account,格式為serviceAccount:[SA_EMAIL_ADDRESS][SA_EMAIL_ADDRESS]為Service Account的[Email],例如serviceaccount1@project-id-1.iam.gserviceaccount.com
  • 第二個參數為iam.RoleName,為要綁定的role名稱。例如這邊為可存取bucket的role [Storage Object Admin](roles/storage.objectAdmin)。

最後呼叫bucket的iam.Handle.SetPolicy將修改好的policy設定回去。

main.go

import (
    "context"
    "fmt"

    "cloud.google.com/go/iam"
    "cloud.google.com/go/storage"
)

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

    storageClient, err := storage.NewClient(ctx)
    if err != nil {
        panic(err)
    }

    bucketName := "[BUCKET_NAME]"
    bucketHandle := storageClient.Bucket(bucketName)
    policy, err := bucketHandle.IAM().Policy(ctx)
    if err != nil {
        panic(err)
    }

    serviceAccountEmail := "[ACCOUNT_ID]@[PROJECT_ID].iam.gserviceaccount.com"
    member := fmt.Sprintf("serviceAccount:%s", serviceAccountEmail)
    storageObjectAdminRole := "roles/storage.objectAdmin"
    policy.Add(member, iam.RoleName(storageObjectAdminRole)) // add the binding of service account with role into bucket's policy

    err = bucketHandle.IAM().SetPolicy(ctx, policy)
    if err != nil {
        panic(err)
    }

}

github




測試

執行後,前往GCP console,在bucket頁面下的[PERMISSIONS]頁籤的[VIEW BY PRINCIPLE]頁籤的[Principle]欄位可看到加入的service account,在[Role]欄位可看到綁定的role。


沒有留言:

AdSense