From c05a1157677dc4f2fbccfee55d635e86d504381c Mon Sep 17 00:00:00 2001 From: Luca Di Maio Date: Thu, 14 Sep 2023 11:18:46 +0200 Subject: [PATCH] fix: support passing Gcloud JSON credentials via Env Signed-off-by: Luca Di Maio --- cmd/init.go | 1 + pkg/gcloud/gcloud.go | 29 ++++++++++++++++++++++++++--- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/cmd/init.go b/cmd/init.go index d100022..3601118 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -2,6 +2,7 @@ package cmd import ( "context" + "github.com/loft-sh/devpod-provider-gcloud/pkg/gcloud" "github.com/loft-sh/devpod-provider-gcloud/pkg/options" "github.com/loft-sh/devpod/pkg/log" diff --git a/pkg/gcloud/gcloud.go b/pkg/gcloud/gcloud.go index 924bc79..8622347 100644 --- a/pkg/gcloud/gcloud.go +++ b/pkg/gcloud/gcloud.go @@ -1,11 +1,15 @@ package gcloud import ( - compute "cloud.google.com/go/compute/apiv1" - computepb "cloud.google.com/go/compute/apiv1/computepb" "context" "encoding/json" "fmt" + "os" + "path/filepath" + "strings" + + compute "cloud.google.com/go/compute/apiv1" + computepb "cloud.google.com/go/compute/apiv1/computepb" "github.com/googleapis/gax-go/v2/apierror" "github.com/loft-sh/devpod/pkg/client" "golang.org/x/oauth2" @@ -13,10 +17,14 @@ import ( "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" - "strings" ) func NewClient(ctx context.Context, project, zone string, opts ...option.ClientOption) (*Client, error) { + err := SetupEnvJson(ctx) + if err != nil { + return nil, err + } + instanceClient, err := compute.NewInstancesRESTClient(ctx, opts...) if err != nil { return nil, err @@ -36,6 +44,21 @@ type Client struct { Zone string } +func SetupEnvJson(ctx context.Context) error { + if os.Getenv("GCLOUD_JSON_AUTH") != "" { + destination := filepath.Join(os.TempDir(), "gcloud_auth.json") + + err := os.WriteFile(destination, []byte(os.Getenv("GCLOUD_JSON_AUTH")), 0o400) + if err != nil { + return err + } + + return os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", destination) + } + + return nil +} + func DefaultTokenSource(ctx context.Context) (oauth2.TokenSource, error) { return google.DefaultTokenSource(ctx) }