Search code examples
terraformterraform-provider-gcp

Terraform Cloud Run Service URL


I create a cloud run service like so

terraform {
  required_version = ">= 1.1.2"
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "~> 4.1.0"
    }
    google-beta = {
      source  = "hashicorp/google-beta"
      version = "~> 4.2.0"
    }
  }
}

provider "google" {
  project     = "main_project"
  region      = "us-central-1"
  credentials = "<my-key-path>"
}

resource "google_cloud_run_service" "default" {
  name     = "cloudrun-srv"
  location = "us-central1"

  template {
    spec {
      containers {
        image = "us-docker.pkg.dev/cloudrun/container/hello"
      }
    }
  }

  traffic {
    percent         = 100
    latest_revision = true
  }
}

I want to save the value of the service url that is created - https://default-hml2qtrgfq-uw.a.run.app using an output variable. something like

output "cloud_run_instance_url" {
  value = google_cloud_run_service.default.url
}

This gives me an error:

terraform plan ╷ │ Error: Unsupported attribute │ │ on main.tf line 40, in output "cloud_run_instance_url": │ 40: value = google_cloud_run_service.default.url │ │ This object has no argument, nested block, or exported attribute named "url". ╵

How do I get this output value and assign it to a variable so that other services like cloud scheduler can point to it?


Solution

  • If you declare an output for the url resource attribute like:

    output "cloud_run_instance_url" {
      value = google_cloud_run_service.default.status.0.url
    }
    

    then it will be available for resolution (such as for inputs to other modules) at the scope where the module is declared in the namespace module.<declared module name>.cloud_run_instance_url. For example, if this module is declared in the root module config, then it can be resolved at that namespace elsewhere in the root module config.