Search code examples
google-cloud-platformterraformgoogle-cloud-run

Is there a way to define Google Cloud Run scheduler triggers using Terraform?


I have a series of CloudRun jobs defined in Terraform (see an example below). In the Google Console UI, I can create Scheduler Triggers to run these jobs like they're cron jobs. Looking over the docs, I don't see a way to define these scheduler triggers using Terraform.

Is there a way / has anyone figured out how to define scheduler triggers for CloudRun jobs using Terraform? If so, would you mind sharing what you did?

resource "google_cloud_run_v2_job" "alltickersfinancials" {
  name     = "tf-alltickersfinancials"
  location = "us-west1"

  template {
    template {
      containers {
        image = "us-west1-docker.pkg.dev/myproject/arapbi/arapbi:latest"
        args  = ["all_financials"]
        resources {
          limits = {
            cpu    = 1
            memory = "2Gi"
          }
        }
        env {
          name = "POLYGON_API_KEY"
          value_source {
            secret_key_ref {
              secret  = "polygon"
              version = "latest"
            }
          }
        }
      }
      timeout         = "900s"
      service_account = "[email protected]"
    }
  }

  lifecycle {
    ignore_changes = [
      launch_stage,
    ]
  }
}

Solution

  • There's an example terraform configuration in the official documentation.

    In your case a basic example would be something like this:

    resource "google_cloud_scheduler_job" "default" {
      name             = "alltickersfinancials"
      schedule         = "*/8 * * * *"
    
      http_target {
        http_method = "POST"
        uri         = "https://${google_cloud_run_v2_job.alltickersfinancials.location}-run.googleapis.com/apis/run.googleapis.com/v1/namespaces/${data.google_project.project.number}/jobs/tf-alltickersfinancials:run"
    
        oauth_token {
          service_account_email = "[email protected]"
        }
      }
    
      depends_on = [
        resource.google_project_service.cloudscheduler_api,
        resource.google_cloud_run_v2_job.alltickersfinancials
      ]
    }