網頁

2024/5/22

Golang 取得GCP Service Account

Go以Google Cloud Client Libraries for Go來取得Service Account。


事前要求

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


取得Service Account

呼叫admin.IamClient.GetServiceAccount建立Service Account,傳入adminpb.GetServiceAccountRequest參數。

adminpb.GetServiceAccountRequest欄位如下:

  • Name - 與Service Account資源名稱,格式為projects/[PROJECT_ID]/serviceAccounts/[ACCOUNT_ID]@[PROJECT_ID].iam.gserviceaccount.com[ACCOUNT_ID]為Service Account的Account ID。

main.go

package main

import (
    "context"
    "fmt"

    admin "cloud.google.com/go/iam/admin/apiv1"
    "cloud.google.com/go/iam/admin/apiv1/adminpb"
)

func main() {
    ctx := context.Background()
    iamClient, err := admin.NewIamClient(ctx)
    if err != nil {
        panic(err)
    }

    sa, err := iamClient.GetServiceAccount(ctx, &adminpb.GetServiceAccountRequest{
        Name: "projects/[PROJECT_ID]/serviceAccounts/[ACCOUNT_ID]@[PROJECT_ID].iam.gserviceaccount.com",
    })
    if err != nil {
        panic(err)
    }

    fmt.Println(sa.GetEmail())     // [ACCOUNT_ID]@[PROJECT_ID].iam.gserviceaccount.com
    fmt.Println(sa.GetName())      // projects/[PROJECT_ID]/serviceAccounts/[ACCOUNT_ID]@[PROJECT_ID].iam.gserviceaccount.com
    fmt.Println(sa.GetProjectId()) // [PROJECT_ID]

}

github



測試

執行後印出以下。

[ACCOUNT_ID]@[PROJECT_ID].iam.gserviceaccount.com
projects/[PROJECT_ID]/serviceAccounts/[ACCOUNT_ID]@[PROJECT_ID].iam.gserviceaccount.com
[PROJECT_ID]

沒有留言:

張貼留言