AdSense

網頁

2024/5/20

Golang 建立GCP Service Account

Go以Google Cloud Client Libraries for Go來建立Service Account。


事前要求

參考「GCP 設定本機應用程式存取憑證 Application Default Credentials」設定credential。


下載modules

在專案根目錄執行以下命令下載需要的API modules。



建立Service Account

呼叫admin.NewIamClient建立admin.IamClient

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

adminpb.CreateServiceAccountRequest欄位如下:

  • Name - 與Service Account關聯的專案名稱,格式為projects/[PROJECT_ID]
  • AccountId - Service 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.CreateServiceAccount(ctx, &adminpb.CreateServiceAccountRequest{
        Name:      "projects/[PROJECT_ID]",
        AccountId: "serviceaccount1",
    })
    if err != nil {
        panic(err)
    }

    fmt.Println(sa.GetName())           // projects/[PROJECT_ID]/serviceAccounts/serviceaccount1@[PROJECT_ID].iam.gserviceaccount.com
    fmt.Println(sa.GetUniqueId())       // 104906904130723564986
    fmt.Println(sa.GetOauth2ClientId()) // 104906904130723564986
}

github



測試

執行後印出以下。

projects/[PROJECT_ID]/serviceAccounts/serviceaccount1@[PROJECT_ID].iam.gserviceaccount.com
104906904130723564986
104906904130723564986


沒有留言:

AdSense