LoginSignup
0

More than 1 year has passed since last update.

posted at

updated at

golangでgcpのサービスアカウントjsonを用いた認証

地味にいろいろ大変だったのでメモ

こんな感じで動いた

package hoge

import (
    "context"
    "os"
    "io/ioutil"

    "golang.org/x/oauth2/google"
    cloudbuild "google.golang.org/api/cloudbuild/v1"
    "google.golang.org/api/option"
)

func initCloudbuildClient() {
    file, err := os.Open("./credentials/your-own-service-account-keyfile.json")
    if err != nil {
        panic(err)
    }
    credentialBytes, err := ioutil.ReadAll(file)
    if err != nil {
        panic(err)
    }

    ctx := context.Background()
    credential, err := google.CredentialsFromJSON(ctx, credentialBytes, "https://www.googleapis.com/auth/cloud-platform")
    if err != nil {
        panic(err)
    }

    // 読み込んだサービスアカウントのcredentialで試しにcloudbuildのクライアントを初期化
    if _, err := cloudbuild.NewService(ctx, option.WithCredentials(credential)); err != nil {
        panic(err)
    }
}

追記: このやり方は認証情報が書かれているjsonファイルを直接保持する手法なので、セキュリティ的にはあまりよろしくない。可能な限りサービスアカウントによる認証か、あるいはWorkload Identity連携を使ったほうがいい。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
0