Search code examples
kubernetesgoogle-cloud-platformgoogle-kubernetes-enginegoogle-api-java-clientgoogle-container-builder

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


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


Solution

  • 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.