Home > Software design >  GO GCP SDK auth code to connect gcp project
GO GCP SDK auth code to connect gcp project

Time:03-23

Im using the following code which works as expected, I use from the cli gcloud auth application-default login and enter my credentials and I was able to run the code successfully from my macbook.

Now I need to run this code in my CI and we need to use different approach , what should be the approach to get the client_secret and client_id or service account / some ENV variable, what is the way for doing it via GO code?

import "google.golang.org/api/compute/v1"

project := "my-project"
region := "my-region"

ctx := context.Background()

c, err := google.DefaultClient(ctx, compute.CloudPlatformScope)
if err != nil {
    log.Fatal(err)
}

computeService, err := compute.New(c)
if err != nil {
    log.Fatal(err)
}

req := computeService.Routers.List(project, region)
if err := req.Pages(ctx, func(page *compute.RouterList) error {
    for _, router := range page.Items {
        // process each `router` resource:
        fmt.Printf("%#v\n", router)
        // NAT Gateways are found in router.nats
    }
    return nil
}); err != nil {
    log.Fatal(err)
}

CodePudding user response:

Since you're using Jenkins you probably want to start with how to create a service account. It guides you on creating a service account and exporting a key to be set as a var in another CI/CD system.

Then refer to the docs from the client library on how to create a new client with source credential.

e.g.

client, err := storage.NewClient(ctx, option.WithCredentialsFile("path/to/keyfile.json"))

If you provided no source, it would attempt to read the credentials locally and act as the service account running the operation (not applicable in your use case).

CodePudding user response:

Many CIs support the export of specific env vars. Or your script / conf can do it too.

But if you want to run in a CI why you need such configuration? Integration tests?

Some services can be used locally for unit/smoke testing. Like pubsub, there is a way to run a fake/local pubsub to perform some tests.

Or perhaps I did not understand your question, in this case can you provide an example?

  • Related