How to run Cloud Endpoints on Cloud Run?

Hi,

I am having some problems while trying to create Cloud Endpoints on a Cloud Run service, mainly because of its “complicated” dependency chain.

So what we would usually do is:

  1. Create a Cloud Run service. Note its URL.
  2. Create a Cloud Endpoints service that refers to URL we got from step 1.
  3. Update the Cloud Run service that we created before, adding an environment variable containing its own URL.
#############
# Cloud Run #
#############
resource "google_cloud_run_service" "cloud-run" {
  name     = "cloud-run"
  provider = "google-beta"
  location = "europe-west1"
  metadata {
    namespace = "${var.gcp_project[var.env]}"
  }
  spec {
    containers {
      env { # STEP 3: update environment variable
        name  = "ENDPOINTS_SERVICE_NAME"
        value = "${local.cloud_run_url}" # <--- pseudo-code, will not work because it is self-referential
      }
      image = "gcr.io/endpoints-release/endpoints-runtime-serverless@sha256:a12b14dd6d31a88637ca7c9e63724ad542226d9509421ba08ed4452a91ce751e"
    }
    container_concurrency = var.env != "dev" ? 0 : 1
  }
}

locals {
  # STEP 1: create Cloud Run and get URL
  cloud_run_url = google_cloud_run_service.cloud-run.status[0].url
}

output "cloudRunUrl" {
  value = local.cloud_run_url
}

###################
# Cloud Endpoints #
###################
resource "google_endpoints_service" "my-api" {
  # STEP 2: Create Cloud Endpoints service with Cloud Run's URL
  service_name = "${replace(local.cloud_run_url, "https://", "")}"
  openapi_config = <<EOF
swagger: '2.0'
info:
  title: My-API
  description: Some description.
  version: 1.0.0
host: "${replace(local.cloud_run_url, "https://", "")}"
security:
  - api_key: []
[...]
EOF

depends_on = ["google_cloud_run_service.cloud-run"}
}

So steps 1 and 2 are working, but I am trying to figure out how to add an environment variable to the Cloud Run service after it has been created, without having to write any references to itself in the configuration.

Any ideas?