I would like to fetch project-id in Go through the service account I am using in my system so that whenever that code runs on a compute instance in GCP, it should retrieve the project-id where the compute instance lies. Also if I run the code from my local machine, it should get the project-id same as "gcloud info" command gets from command line.
Does anyone have any idea which API to use in Go?
Figured out the correct API.
package main
import (
"fmt"
"golang.org/x/net/context"
"google.golang.org/api/compute/v1"
"golang.org/x/oauth2/google"
)
func main() {
ctx := context.Background()
credentials, err := google.FindDefaultCredentials(ctx,compute.ComputeScope)
if err != nil {
fmt.Println(err)
}
fmt.Printf(credentials.ProjectID)
}
You can find out the project ID of the Compute Engine instance by using the Google Cloud API [1] with a GET request to “ http://metadata.google.internal/computeMetadata/v1/project/project-id ” with the header “Metadata-Flavor: Google” in order to be allowed.
It can be tested in the Cloud Shell or a secure shell (SSH) terminal by using:
curl " http://metadata.google.internal/computeMetadata/v1/project/project-id " -H "Metadata-Flavor: Google"
[1] : https://cloud.google.com/compute/docs/storing-retrieving-metadata#default
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.