1 // Copyright 2022 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package gcp 16 17 import ( 18 "context" 19 "fmt" 20 "os/exec" 21 "strings" 22 23 "golang.org/x/oauth2/google" 24 sqladmin "google.golang.org/api/sqladmin/v1beta4" 25 ) 26 27 // GetDefaultProjectID tries to retrieve the default project id through the following: 28 // 1. Grabbing the project id specified in the application-default GCP credentials on the host machine. This often 29 // returns an error, for example when the application-default credentials are expired. Also, the default credentials 30 // often do not have the project id set (it's set when the credentials are for a service account). 31 // 2. If, in step 1 above, there is an error or the project id field is blank, then silently ignore the failure, and 32 // fall back to shelling out to gcloud to get the default project id from the local gcloud config. 33 func GetDefaultProjectID() (string, error) { 34 creds, err := google.FindDefaultCredentials(context.Background(), sqladmin.CloudPlatformScope) 35 if err == nil && creds.ProjectID != "" { 36 return creds.ProjectID, nil 37 } 38 return getGCloudDefaultProjectID() 39 } 40 41 func getGCloudDefaultProjectID() (string, error) { 42 cmd := exec.Command("gcloud", "config", "get-value", "project") 43 bytes, err := cmd.Output() 44 if err != nil { 45 return "", fmt.Errorf("error executing command '%v': %v'", cmd, err) 46 } 47 value := string(bytes) 48 if value == "" { 49 return "", fmt.Errorf("error getting default project: gcloud config value for 'project' is empty") 50 } 51 return strings.TrimSpace(string(bytes)), nil 52 } 53