Google cloud run: Can a service know its own url?

Viewed 1294

I'm wondering if a container deployed on cloud run can somehow obtain its own service url or is it impossible?

I'm wanting to know this because I want a cloud run worker that creates google cloud tasks for itself.

If it is possible, how can it be done?

3 Answers

Use namespaces.services.get to retrieve the cloud run service info, some information required for this api

  1. Service name

    Cloud Run has provided default environment variable K_SERVICE

  2. Project ID

  3. Region

  4. Access token

Project ID, region and access token can retrieve from metadata server

PROJECT_ID=$(curl "http://metadata.google.internal/computeMetadata/v1/project/project-id" -H "Metadata-Flavor: Google")
REGION=$(curl "http://metadata.google.internal/computeMetadata/v1/instance/region" -H "Metadata-Flavor: Google" | sed "s/.*\///")
TOKEN=$(curl -s "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token" -H "Metadata-Flavor: Google" | jq -r '.access_token')

Then you can use namespaces.services.get to retrieve the cloud run service info in json, extract url with jq, export environment variable for application use

export PUCLIC_URL=$(curl -s "https://${REGION}-run.googleapis.com/apis/serving.knative.dev/v1/namespaces/${PROJECT_ID}/services/${K_SERVICE}" -H "Authorization: Bearer ${TOKEN}" | jq -r '.status.url')

curl and jq may required to install, for alpine: apk add --no-cache curl jq

Cloud Run service account requires run.services.get permission to call namespaces.services.get

If you know the service name, you can make a GET HTTP request to https://{endpoint}/apis/serving.knative.dev/v1/{name}

Method: namespaces.services.get

For example :

curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)"  https://us-central1-run.googleapis.com/apis/serving.knative.dev/v1/namespaces/your-project/services/your-service| grep url

"url": "https://cloud-run-xxxxxxxxxx-uc.a.run.app"
Related