How to get programmatically the current GKE project id from one of its clusters?

5/28/2019

I'd like to get the current GKE project id from within one of its clusters via the Java client or the GCloud API itself.

  • I'm running java containers in a GKE cluster of a specific Google Cloud project
  • I initialize the ClusterManagerClient with the appropriate ClusterManagerSettings

-> Is it possible to fetch this specific project id with this client?

(I'm expecting that there would be a global context within each GKE cluster where we could know the current project we're running on).

Thank you

-- Vlad
google-api-java-client
google-cloud-platform
google-container-builder
google-kubernetes-engine
kubernetes

1 Answer

5/28/2019

As John Hanley mentioned in his comment above, you can use the instance metadata on the node in your cluster to determine the project that the node is a part of. The easiest way to see it is to use curl from a shell (either on the node or in a container).

If you want the project name, it can be seen at:

curl "http://metadata.google.internal/computeMetadata/v1/project/project-id" -H "Metadata-Flavor: Google"

And if you want the project number, it can be seen at:

curl "http://metadata.google.internal/computeMetadata/v1/project/numeric-project-id" -H "Metadata-Flavor: Google"

This isn't part of the container API surface, so the ClusterManagerClient isn't the right API client to use. You need to create a client to fetch the instance metadata, which I would expect might be part of the compute client libraries, or you can just make a local HTTP request if you add the right headers (as shown above) since you don't need any special client authentication / authorization to access the local metadata.

-- Robert Bailey
Source: StackOverflow