How to get instanceid from cloud_run?

3.4k Views Asked by At

The logs from cloud run spit out some good json with resource.labels.revision_name = my_name-00046-kip.

The json path labels.instanceId is more like this though

00bf4bf02d71261c0c1f55a601331b336a5d90d365cca1b28330dcf3e456fb7c07d5b72f1d3c9a971e391b5edc3512aea8559d172b24e639

per this document I was able to get revision_name

https://cloud.google.com/run/docs/reference/container-contract#env-vars

but I can't get the instance id and metrics must be reported per instance or two instances reporting in the same minute will be rejected. how do I get instance id (preferably through DockerFile and if not through api call). If cloud run boots up 10 instances under one revision name, I have to make sure to uniquely report metrics to Generic Task resource where I plan on filling in job_id with the instance id.

thanks, Dean

3

There are 3 best solutions below

0
On BEST ANSWER

Please try using the metadata server to get the instance ID using the url:

http://metadata.google.internal/computeMetadata/v1/instance/id

Note that "Metadata-Flavor: Google" header is also required.

0
On

If you're using Java (as indicated by the tags), the easiest way to get the instance ID from the "internal metadata server" programmatically is probably to include the dependency com.google.cloud:google-cloud-core:1.93.5 (or newer) through Gradle/Maven and then call the following method:

import com.google.cloud.MetadataConfig;

String instanceId = MetadataConfig.getInstanceId();
0
On

The entries in the logging in Stackdriver is as follows

labels: {
  instanceId: "00bf4bf02d4b374e91dda64bc4c4241a218302c4bcc73a01ecf85e582127e8c8076fcbe18b3cc934f5ed33e5dc1348c58cfd40cbecc0c9ae2a0b6d2356"   
 }

  labels: {
   configuration_name: "cloudrunservice"    
   location: "us-central1"    
   project_id: "xxxx-xxxx-000"    
   revision_name: "cloudrunservice-00002-leq"    
   service_name: "cloudrunservice"    
  }
  type: "cloud_run_revision" 

As you mentioned, each one has the instance Id, Revision name, and Service name. In this way, you do not have to worry about rejected entries in the logging by the same instance / time.

I could no see something related with the instances ID in the UI, managing Revisions. Handling this JSON from logging you could get the InsanceID.