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]
}
測試
執行後印出以下。
[ACCOUNT_ID]@[PROJECT_ID].iam.gserviceaccount.com
projects/[PROJECT_ID]/serviceAccounts/[ACCOUNT_ID]@[PROJECT_ID].iam.gserviceaccount.com
[PROJECT_ID]
沒有留言:
張貼留言