1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

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

Last updated at Posted at 2022-04-06

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

こんな感じで動いた

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連携を使ったほうがいい。

1
0
0

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
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?