Skip to content

Instantly share code, notes, and snippets.

@joemiller
Last active January 29, 2020 22:56
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save joemiller/193e38a9bc1dce5090d377e5ef368659 to your computer and use it in GitHub Desktop.
gceProject() golang function that implements multiple methods of determining the GCP project it is being run within
package main
import (
"context"
"errors"
"log"
"os"
"time"
"golang.org/x/oauth2/google"
)
func main() {
project, err := gceProject()
if err != nil {
log.Fatal(err)
}
log.Println(project)
}
// gceProject attempts to determine the GCE Project that it is running within.
// The controller needs this information because it is not available on any of the
// objects monitored by the controller (PV, PVC, nor PD).
//
// It looks for the project in the following order:
// 1. env var GOOGLE_PROJECT
// 2. APPLICATION_DEFAULT_CREDENTIALS - https://github.com/golang/oauth2/blob/HEAD/google/default.go#L61-L75
// a. A JSON file whose path is specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable.
// b. A JSON file in a location known to the gcloud command-line tool.
// On Windows, this is %APPDATA%/gcloud/application_default_credentials.json.
// On other systems, $HOME/.config/gcloud/application_default_credentials.json.
// c. On Google App Engine standard first generation runtimes (<= Go 1.9) it uses
// the appengine.AccessToken function.
// d. On Google Compute Engine, Google App Engine standard second generation runtimes
// (>= Go 1.11), and Google App Engine flexible environment, it fetches
// credentials from the metadata server.
func gceProject() (string, error) {
// 1 - environment GOOGLE_PROJECT
if project := os.Getenv("GOOGLE_PROJECT"); project != "" {
log.Println("DEBUG: found project via environment") // you can remove this, or replace with your own logger
return project, nil
}
// 2 - ADC: https://github.com/golang/oauth2/blob/HEAD/google/default.go#L61-L75
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
credentials, err := google.FindDefaultCredentials(ctx)
if err == nil {
if credentials.ProjectID != "" {
log.Println("DEBUG: found project via APPLICATION_DEFAULT_CREDENTIALS") // you can remove this, or replace with your own logger
return credentials.ProjectID, nil
}
}
return "", errors.New("Unable to automatically determine Google Cloud Project. You must set the env var 'GOOGLE_PROJECT'")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment