Files
hunfabric/modules/cloud-run-v2/README.md
Julio Castillo 2eaa0d5e27 Add support for dynamic tags (#3897)
* Allow creation of dynamic tags

* Extend project factory and related modules to support dynamic values

* Extend folder and organization modules

* project and organization readme

* Simplify dynamic tag support and remove unnecessary restrictions

  • Schemas & Validations: Removed the restriction that forbade combining IAM fields with  allowed_values_regex  on tags. Updated validations in  project  and  organization  modules, and
  simplified all relevant JSON schemas.
  • Module Tag Bindings: Simplified the  tag_value  assignment in  folder ,  project ,  gcs ,  bigquery-dataset , and  kms  modules by removing the defensive  can(regex(...))  check and
  calling  templatestring  directly.
  • Outputs: Removed the  tags_dynamic  output from  project  and  organization  modules, as the same information is now available in  tag_keys .
  • Project Factory: Updated  tag_vars_projects  in  projects.tf  to use the native  namespaced_name  attribute and filtered manually for dynamic tags.

* fix(organization, project): fix linting and tests for dynamic tag support

- Align allowed_values_regex and description extraction in _tags_merged
  locals to use lookup() for consistency with other fields.
- Fix spacing in project context variable (alphabetical ordering).
- Update organization tags test to include the new cost_center tag key
  with allowed_values_regex.
- Update project tags test to include the new cost_center tag key and
  reflect the resolved allowed_values_regex on environment.

* refactor(gcs): refine tag bindings and fix context test

- Add _tag_bindings local to pre-resolve context references, enabling
  templatestring to receive a direct map reference (required by Terraform).
- Use var.context.tag_vars instead of the non-existent local.ctx.tag_vars.
- Fix HCL syntax in context.tfvars (escaped inner quotes).
- Update context test inventory to reflect 3 tag bindings including a
  dynamic value resolved via templatestring.

* refactor: align modules with tag binding context pattern

- Add _tag_bindings local + templatestring dance to cloud-run-v2,
  compute-vm, folder, kms modules (bigquery-dataset already had it)
- Exclude tag_vars from local.ctx in cloud-run-v2, compute-vm, folder,
  kms, project modules (bigquery-dataset already had it)
- Add tag_vars to context variable in cloud-run-v2, compute-vm modules
  (others already had it)
- Update all context tests with dynamic tag binding values using
  var.context.tag_vars

* docs: add module-level tftest.yaml test instructions to GEMINI.md

* docs: regenerate READMEs after tag-regex alignment

- Regenerate variable tables in 7 module READMEs to reflect
  line number shifts from prior tag-regex changes
- Add tag_vars exclusion to gcs ctx local
- Fix whitespace alignment in iam-service-account and
  project-factory tag_vars blocks
- Update tftest resource counts for organization and project
- Remove tags_dynamic from organization/project output tables

* fix(project-factory): update test inventory for tag_bindings module split

- Move tag binding address from folder-2 to folder-2-iam in test
  inventory (tag_bindings moved from creation to IAM modules)
- Update module instance count from 34 to 35
- Regenerate README tables after terraform fmt line shifts
- Apply terraform fmt to variables.tf

* refactor(project-factory): remove unnecessary depends_on from folder-iam modules

Folder IAM modules depend on their own folder creation modules, not
on module.projects. The explicit depends_on was leftover from an
earlier design.

* FAST stages

* Address review comments.

- FAST Stages:
  - Added tag_keys to output-files.tf in 0-org-setup to pass org tags via tfvars.
  - Sorted tag_keys and tag_values in output-files.tf.
  - Updated project-factory, networking, and security stages to use tag_keys.
  - Filtered tag_keys for dynamic tags only.
- Modules:
  - Excluded tag_vars from local.ctx in iam-service-account and organization.
  - Simplified tag_value in iam-service-account.
- Tests:
  - Updated test inventories for 0-org-setup and project-factory.

* Fix tf format

* Fix tfdoc

* docs: add ADR for templatestring vars convention and update status of base path ADR

* More tfdoc

* Update schemas

* Use endswith in context loop

* Address review

* Update FAST readmes

* Update last modules

* Terraform fmt

* Revert alloydb

* Fix whitespace

---------

Co-authored-by: Ludovico Magnocavallo <ludo@qix.it>
2026-04-24 20:45:45 +00:00

31 KiB

Cloud Run Module

Cloud Run Services and Jobs, with support for IAM roles and Eventarc trigger creation. This module uses provider default value for deletion_protection, which means service is by default protected from removal (or reprovisioning).

IAM and environment variables

IAM bindings support the usual syntax. Container environment values can be declared as key-value strings or as references to Secret Manager secrets. Both can be combined as long as there is no duplication of keys:

module "cloud_run" {
  source     = "./fabric/modules/cloud-run-v2"
  project_id = var.project_id
  name       = "example-hello"
  region     = var.region
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
      env = {
        VAR1 = "VALUE1"
        VAR2 = "VALUE2"
      }
      env_from_key = {
        SECRET1 = {
          secret  = module.secret-manager.secrets["credentials"].name
          version = module.secret-manager.version_versions["credentials/v1"]
        }
      }
    }
  }
  iam = {
    "roles/run.invoker" = ["allUsers"]
  }
  deletion_protection = false
}
# tftest fixtures=fixtures/secret-credentials.tf inventory=service-iam-env.yaml e2e skip-tofu

Mounting secrets as volumes

module "cloud_run" {
  source     = "./fabric/modules/cloud-run-v2"
  project_id = var.project_id
  name       = "example-hello"
  region     = var.region
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
      volume_mounts = {
        "credentials" = "/credentials"
      }
    }
  }
  volumes = {
    credentials = {
      secret = {
        name    = module.secret-manager.secrets["credentials"].id
        path    = "my-secret"
        version = "latest" # TODO: should be optional, but results in API error
      }
    }
  }
  deletion_protection = false
}
# tftest fixtures=fixtures/secret-credentials.tf inventory=service-volume-secretes.yaml e2e skip-tofu

Mounting GCS buckets

module "cloud_run" {
  source     = "./fabric/modules/cloud-run-v2"
  project_id = var.project_id
  name       = "example-hello"
  region     = var.region
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
      volume_mounts = {
        bucket = "/bucket"
      }
    }
  }
  service_config = {
    gen2_execution_environment = true
  }
  volumes = {
    bucket = {
      gcs = {
        bucket       = var.bucket
        is_read_only = false
        mount_options = [ # Beta feature
          "metadata-cache-ttl-secs=120s",
          "type-cache-max-size-mb=4",
        ]
      }
    }
  }
  deletion_protection = false
}
# tftest inventory=gcs-mount.yaml e2e

Connecting to Cloud SQL database

module "cloud_run" {
  source     = "./fabric/modules/cloud-run-v2"
  project_id = var.project_id
  region     = var.region
  name       = "example-hello"
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
      volume_mounts = {
        cloudsql = "/cloudsql"
      }
    }
  }
  volumes = {
    "cloudsql" = {
      cloud_sql_instances = [module.cloudsql-instance.connection_name]
    }
  }
  deletion_protection = false
}
# tftest fixtures=fixtures/cloudsql-instance.tf inventory=cloudsql.yaml e2e

Direct VPC Egress

module "cloud_run" {
  source     = "./fabric/modules/cloud-run-v2"
  project_id = var.project_id
  name       = "example-hello"
  region     = var.region
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
    }
  }
  revision = {
    vpc_access = {
      egress = "ALL_TRAFFIC"
      subnet = var.subnet.name
      tags   = ["tag1", "tag2", "tag3"]
    }
  }
  service_config = {
    gen2_execution_environment = true
    max_instance_count         = 20
  }
  deletion_protection = false
}
# E2E test disabled due to b/332419038
# tftest inventory=service-direct-vpc.yaml

VPC Access Connector

You can use an existing VPC Access Connector to connect to a VPC from Cloud Run.

module "cloud_run" {
  source     = "./fabric/modules/cloud-run-v2"
  project_id = var.project_id
  region     = var.regions.secondary
  name       = "example-hello"
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
    }
  }
  service_config = {
    vpc_access = {
      connector = google_vpc_access_connector.connector.id
      egress    = "ALL_TRAFFIC"
    }
  }
  deletion_protection = false
}
# tftest fixtures=fixtures/vpc-connector.tf inventory=service-vpc-access-connector.yaml e2e

If creation of the VPC Access Connector is required, use the vpc_connector_create variable which also supports optional attributes like number of instances, machine type, or throughput. The connector will be used automatically by Cloud Run Service and Job. Worker Pool does not support connector.

module "cloud_run" {
  source     = "./fabric/modules/cloud-run-v2"
  project_id = var.project_id
  region     = var.region
  name       = "example-hello"
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
    }
  }
  vpc_connector_create = {
    ip_cidr_range = "10.10.10.0/28"
    network       = var.vpc.self_link
    instances = {
      max = 10
      min = 3
    }
  }
  deletion_protection = false
}
# tftest inventory=service-vpc-access-connector-create.yaml e2e

Note that if you are using a Shared VPC for the connector, you need to specify a subnet and the host project if this is not where the Cloud Run service is deployed.

module "cloud_run" {
  source     = "./fabric/modules/cloud-run-v2"
  project_id = module.project-service.project_id
  region     = var.region
  name       = "example-hello"
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
    }
  }
  vpc_connector_create = {
    machine_type = "e2-standard-4"
    subnet = {
      name       = module.net-vpc-host.subnets["${var.region}/fixture-subnet-28"].name
      project_id = module.project-host.project_id
    }
    throughput = {
      max = 300
      min = 200
    }
  }
  deletion_protection = false
}
# tftest fixtures=fixtures/shared-vpc.tf inventory=service-vpc-access-connector-create-sharedvpc.yaml e2e

Using Customer-Managed Encryption Key

Deploy a Cloud Run service with environment variables encrypted using a Customer-Managed Encryption Key (CMEK). Ensure you specify the encryption_key with the full resource identifier of your Cloud KMS CryptoKey and that Cloud Run Service agent (service-<PROJECT_NUMBER>@serverless-robot-prod.iam.gserviceaccount.com) has permission to use the key, for example roles/cloudkms.cryptoKeyEncrypterDecrypter IAM role. This setup adds an extra layer of security by utilizing your own encryption keys.

module "project" {
  source          = "./fabric/modules/project"
  name            = "cloudrun"
  billing_account = var.billing_account_id
  prefix          = var.prefix
  parent          = var.folder_id
  services = [
    "cloudkms.googleapis.com",
    "run.googleapis.com",
  ]
}

module "kms" {
  source     = "./fabric/modules/kms"
  project_id = module.project.project_id
  keyring = {
    location = var.region
    name     = "${var.prefix}-keyring"
  }
  keys = {
    "key-regional" = {
    }
  }
  iam = {
    "roles/cloudkms.cryptoKeyEncrypterDecrypter" = [
      module.project.service_agents.run.iam_email
    ]
  }
}

module "cloud_run" {
  source         = "./fabric/modules/cloud-run-v2"
  project_id     = module.project.project_id
  region         = var.region
  name           = "example-hello"
  encryption_key = module.kms.keys.key-regional.id
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
    }
  }
  deletion_protection = false
}
# tftest inventory=cmek.yaml e2e

Deploying OpenTelemetry Collector sidecar

# Reference: https://cloud.google.com/stackdriver/docs/instrumentation/opentelemetry-collector-cloud-run#gotc-provided-config

receivers:
  # Open two OTLP servers:
  # - On port 4317, open an OTLP GRPC server
  # - On port 4318, open an OTLP HTTP server
  #
  # Docs:
  # https://github.com/open-telemetry/opentelemetry-collector/tree/main/receiver/otlpreceiver
  otlp:
    protocols:
      grpc:
        endpoint: localhost:4317
      http:
        cors:
          # This effectively allows any origin
          # to make requests to the HTTP server.
          allowed_origins:
          - http://*
          - https://*
        endpoint: localhost:4318

  # Using the prometheus scraper, scrape the Collector's self metrics.
  #
  # Docs:
  # https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/prometheusreceiver
  # https://opentelemetry.io/docs/collector/internal-telemetry/
  prometheus/self-metrics:
    config:
      scrape_configs:
      - job_name: otel-self-metrics
        scrape_interval: 1m
        static_configs:
        - targets:
          - localhost:8888

processors:
  # The batch processor is in place to regulate both the number of requests
  # being made and the size of those requests.
  #
  # Docs:
  # https://github.com/open-telemetry/opentelemetry-collector/tree/main/processor/batchprocessor
  batch:
    send_batch_max_size: 200
    send_batch_size: 200
    timeout: 5s

  # The memorylimiter will check the memory usage of the collector process.
  #
  # Docs:
  # https://github.com/open-telemetry/opentelemetry-collector/tree/main/processor/memorylimiterprocessor
  memory_limiter:
    check_interval: 1s
    limit_percentage: 65
    spike_limit_percentage: 20

  # The resourcedetection processor is configured to detect GCP resources.
  # Resource attributes that represent the GCP resource the collector is
  # running on will be attached to all telemetry that goes through this
  # processor.
  #
  # Docs:
  # https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/processor/resourcedetectionprocessor
  # https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/processor/resourcedetectionprocessor#gcp-metadata
  resourcedetection:
    detectors: [gcp]
    timeout: 10s

  # The transform/collision processor ensures that any attributes that may
  # collide with the googlemanagedprometheus exporter's monitored resource
  # construction are moved to a similar name that is not reserved.
  transform/collision:
    metric_statements:
    - context: datapoint
      statements:
      - set(attributes["exported_location"], attributes["location"])
      - delete_key(attributes, "location")
      - set(attributes["exported_cluster"], attributes["cluster"])
      - delete_key(attributes, "cluster")
      - set(attributes["exported_namespace"], attributes["namespace"])
      - delete_key(attributes, "namespace")
      - set(attributes["exported_job"], attributes["job"])
      - delete_key(attributes, "job")
      - set(attributes["exported_instance"], attributes["instance"])
      - delete_key(attributes, "instance")
      - set(attributes["exported_project_id"], attributes["project_id"])
      - delete_key(attributes, "project_id")

exporters:
  # The googlecloud exporter will export telemetry to different
  # Google Cloud services:
  # Logs -> Cloud Logging
  # Metrics -> Cloud Monitoring
  # Traces -> Cloud Trace
  #
  # Docs:
  # https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/exporter/googlecloudexporter
  googlecloud:
    log:
      default_log_name: opentelemetry-collector

  # The googlemanagedprometheus exporter will send metrics to
  # Google Managed Service for Prometheus.
  #
  # Docs:
  # https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/exporter/googlemanagedprometheusexporter
  googlemanagedprometheus:

extensions:
  # Opens an endpoint on 13133 that can be used to check the
  # status of the collector. Since this does not configure the
  # `path` config value, the endpoint will default to `/`.
  #
  # When running on Cloud Run, this extension is required and not optional.
  # In other environments it is recommended but may not be required for operation
  # (i.e. in Container-Optimized OS or other GCE environments).
  #
  # Docs:
  # https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/extension/healthcheckextension
  health_check:
    endpoint: 0.0.0.0:13133

service:
  extensions:
  - health_check
  pipelines:
    logs:
      receivers:
      - otlp
      processors:
      - resourcedetection
      - memory_limiter
      - batch
      exporters:
      - googlecloud
    metrics/otlp:
      receivers:
      - otlp
      processors:
      - transform/collision
      - resourcedetection
      - memory_limiter
      - batch
      exporters:
      - googlemanagedprometheus
    metrics/self-metrics:
      receivers:
      - prometheus/self-metrics
      processors:
      - resourcedetection
      - memory_limiter
      - batch
      exporters:
      - googlemanagedprometheus
    traces:
      receivers:
      - otlp
      processors:
      - resourcedetection
      - memory_limiter
      - batch
      exporters:
      - googlecloud
  telemetry:
    metrics:
      address: localhost:8888

# tftest-file id=otel-config path=config/otel-config.yaml
module "secrets" {
  source     = "./fabric/modules/secret-manager"
  project_id = var.project_id
  secrets = {
    otel-config = {
      iam = {
        "roles/secretmanager.secretAccessor" = [module.cloud_run.service_account_iam_email]
      }
      versions = {
        v1 = {
          data = file("${path.module}/config/otel-config.yaml")
        }
      }
    }
  }
}
module "cloud_run" {
  source     = "./fabric/modules/cloud-run-v2"
  project_id = var.project_id
  region     = var.region
  name       = "example-hello"
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
      ports = {
        default = {
          container_port = 3000
        }
      }
      depends_on = ["collector"]
    }
    collector = {
      image = "us-docker.pkg.dev/cloud-ops-agents-artifacts/google-cloud-opentelemetry-collector/otelcol-google:0.122.1"
      startup_probe = {
        http_get = {
          path = "/"
          port = 13133
        }
        timeout_seconds = 30
        period_seconds  = 30
      }
      liveness_probe = {
        http_get = {
          path = "/"
          port = 13133
        }
        timeout_seconds = 30
        period_seconds  = 30
      }
      volume_mounts = {
        "otel-config" = "/etc/otelcol-google/"
      }
    }
  }
  volumes = {
    otel-config = {
      secret = {
        name    = "otel-config"
        version = "1"
        path    = "config.yaml"
      }
    }
  }
  deletion_protection = false
}
# tftest files=otel-config inventory=service-otel-sidecar.yaml e2e skip-tofu

Eventarc triggers

PubSub

This deploys a Cloud Run service that will be triggered when messages are published to Pub/Sub topics.

module "cloud_run" {
  source     = "./fabric/modules/cloud-run-v2"
  project_id = var.project_id
  region     = var.region
  name       = "example-hello"
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
    }
  }
  service_config = {
    eventarc_triggers = {
      pubsub = {
        topic-1 = module.pubsub.topic.name
      }
    }
  }
  deletion_protection = false
}
# tftest fixtures=fixtures/pubsub.tf inventory=service-eventarc-pubsub.yaml e2e

Audit logs

This deploys a Cloud Run service that will be triggered when specific log events are written to Google Cloud audit logs.

module "cloud_run" {
  source     = "./fabric/modules/cloud-run-v2"
  project_id = var.project_id
  region     = var.region
  name       = "example-hello"
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
    }
  }
  service_config = {
    eventarc_triggers = {
      audit_log = {
        setiampolicy = {
          method  = "SetIamPolicy"
          service = "cloudresourcemanager.googleapis.com"
        }
      }
      service_account_email = module.iam-service-account.email
    }
  }
  iam = {
    "roles/run.invoker" = [module.iam-service-account.iam_email]
  }
  deletion_protection = false
  depends_on          = [google_project_iam_member.eventarc_receiver]
}

resource "google_project_iam_member" "eventarc_receiver" {
  project = var.project_id
  role    = "roles/eventarc.eventReceiver"
  member  = module.iam-service-account.iam_email
}
# tftest fixtures=fixtures/iam-service-account.tf inventory=service-eventarc-auditlogs-external-sa.yaml e2e

GCS bucket

This deploys a Cloud Run service that will be triggered when files are uploaded to a GCS bucket.

module "cloud_run" {
  source     = "./fabric/modules/cloud-run-v2"
  project_id = var.project_id
  region     = var.region
  name       = "example-hello"
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
    }
  }
  service_config = {
    eventarc_triggers = {
      storage = {
        bucket-upload = {
          bucket = module.gcs.name
          path   = "/webhook" # optional: URL path for the Cloud Run service
        }
      }
      service_account_email = module.iam-service-account.email
    }
  }
  deletion_protection = false
  depends_on = [
    google_project_iam_member.gcs_pubsb_publisher,
    google_project_iam_member.trigger_sa_event_receiver,
  ]
}

resource "google_project_iam_member" "trigger_sa_event_receiver" {
  member  = module.iam-service-account.iam_email
  project = var.project_id
  role    = "roles/eventarc.eventReceiver"
}

resource "google_project_iam_member" "gcs_pubsb_publisher" {
  member  = "serviceAccount:service-${var.project_number}@gs-project-accounts.iam.gserviceaccount.com"
  project = var.project_id
  role    = "roles/pubsub.publisher"
}

# tftest fixtures=fixtures/gcs.tf,fixtures/iam-service-account.tf inventory=service-eventarc-storage.yaml e2e

Cloud Run Invoker IAM Disable

To disables IAM permission check for run.routes.invoke for callers of this service set the invoker_iam_disabled variable of the module to true (default false). There should be no requirement to pass the roles/run.invoker to the IAM block to enable public access. This allows for the org policy domain restricted sharing org policy remain enabled.

module "cloud_run" {
  source     = "./fabric/modules/cloud-run-v2"
  project_id = var.project_id
  region     = var.region
  name       = "example-hello"
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
    }
  }
  service_config = {
    invoker_iam_disabled = true
  }
  deletion_protection = false
}
# tftest inventory=service-invoker-iam-disable.yaml e2e

Cloud Run Service Account

The module by default creates a service account that is associated with the Cloud Run instance. It grants the service account roles/logging.logWriter and roles/monitoring.metricWriter roles.

To assign non-default roles, pass them as service_account_config.roles.

module "cloud_run" {
  source     = "./fabric/modules/cloud-run-v2"
  project_id = var.project_id
  region     = var.region
  name       = "example-hello"
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
    }
  }
  service_account_config = {
    roles = [
      "roles/logging.logWriter",
      "roles/monitoring.metricWriter",
      "roles/cloudsql.client",
      "roles/cloudsql.instanceUser",
    ]
  }
  deletion_protection = false
}
# tftest inventory=service-sa-create.yaml e2e

To use externally managed service account, pass its email in service_account_config.email and set service_account_config.email to false.

module "cloud_run" {
  source     = "./fabric/modules/cloud-run-v2"
  project_id = var.project_id
  region     = var.region
  name       = "example-hello"
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
    }
  }
  service_account_config = {
    create = false
    email  = module.iam-service-account.email
  }
  deletion_protection = false
}
# tftest fixtures=fixtures/iam-service-account.tf inventory=service-external-sa.yaml e2e

Creating Cloud Run Jobs

To create a job instead of service set type to JOB. Jobs support all functions above apart from triggers.

Unsupported variables / attributes:

  • ingress
  • revision.gen2_execution_environment (they run by default in gen2)
  • revision.name
  • containers.liveness_probe
  • containers.startup_probe
  • containers.resources.cpu_idle
  • containers.resources.startup_cpu_boost

Additional configuration can be passwed as job_config:

  • max_retries - maximum of retries per task
  • task_count - desired number of tasks
  • timeout - max allowed time per task, in seconds with up to nine fractional digits, ending with 's'. Example: 3.5s
module "cloud_run" {
  source     = "./fabric/modules/cloud-run-v2"
  project_id = var.project_id
  name       = "example-hello"
  region     = var.region
  type       = "JOB"
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
      env = {
        VAR1 = "VALUE1"
        VAR2 = "VALUE2"
      }
    }
  }
  iam = {
    "roles/run.invoker" = ["group:${var.group_email}"]
  }
  deletion_protection = false
}

# tftest inventory=job-iam-env.yaml e2e

Tag bindings

Tag bindings are not yet supported for Worker Pool. Refer to the Creating and managing tags documentation for details on usage.

module "project" {
  source = "./fabric/modules/project"
  name   = var.project_id
  project_reuse = {
    use_data_source = false
    attributes = {
      name   = var.project_id
      number = var.project_number
    }
  }
  tags = {
    run_environment = {
      description = "Environment specification."
      values = {
        dev     = {}
        prod    = {}
        sandbox = {}
      }
    }
  }
}

module "cloud_run_service" {
  source     = "./fabric/modules/cloud-run-v2"
  project_id = var.project_id
  name       = "hello-service"
  region     = var.region
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
    }
  }
  tag_bindings = {
    env-sandbox = module.project.tag_values["run_environment/sandbox"].id
  }
  deletion_protection = false
}

module "cloud_run_job" {
  source     = "./fabric/modules/cloud-run-v2"
  project_id = var.project_id
  name       = "hello-job"
  region     = var.region
  type       = "JOB"
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
    }
  }
  tag_bindings = {
    env-sandbox = module.project.tag_values["run_environment/sandbox"].id
  }
  deletion_protection = false
}

# tftest inventory=tags.yaml e2e

IAP Configuration

IAP is only supported for service. Refer to the Configure IAP directly on cloud run documentation for details on usage.

module "cloud_run" {
  source     = "./fabric/modules/cloud-run-v2"
  project_id = var.project_id
  name       = "example-hello"
  region     = var.region
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
    }
  }
  service_config = {
    iap_config = {
      iam = ["group:${var.group_email}"]
    }
  }
  deletion_protection = false
}
# tftest inventory=iap.yaml e2e

Adding GPUs

GPU support is available for all types of Cloud Run resources: jobs, services and worker pools.

module "job" {
  source       = "./fabric/modules/cloud-run-v2"
  project_id   = var.project_id
  name         = "example-job"
  region       = var.region
  launch_stage = "BETA"
  revision = {
    gpu_zonal_redundancy_disabled = true
    node_selector = {
      accelerator = "nvidia-l4"
    }
  }
  type = "JOB"
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
      resources = {
        limits = {
          cpu              = "4000m"
          memory           = "16Gi"
          "nvidia.com/gpu" = "1"
        }
      }
    }
  }
  deletion_protection = false
}
# tftest inventory=gpu-job.yaml
module "service" {
  source     = "./fabric/modules/cloud-run-v2"
  project_id = var.project_id
  name       = "service"
  region     = var.region
  revision = {
    gpu_zonal_redundancy_disabled = true
    node_selector = {
      accelerator = "nvidia-l4"
    }
  }
  service_config = {
    gen2_execution_environment = true
  }
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
      resources = {
        limits = {
          cpu              = "4000m"
          memory           = "16Gi"
          "nvidia.com/gpu" = "1"
        }
      }
    }
  }
  deletion_protection = false
}
# tftest inventory=gpu-service.yaml e2e
module "worker" {
  source       = "./fabric/modules/cloud-run-v2"
  project_id   = var.project_id
  name         = "worker"
  region       = var.region
  launch_stage = "BETA"
  revision = {
    gpu_zonal_redundancy_disabled = true
    node_selector = {
      accelerator = "nvidia-l4"
    }
  }
  type = "WORKERPOOL"
  containers = {
    hello = {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
      resources = {
        limits = {
          cpu              = "4000m"
          memory           = "16Gi"
          "nvidia.com/gpu" = "1"
        }
      }
    }
  }
  deletion_protection = false
}
# tftest inventory=gpu-workerpool.yaml e2e

Variables

name description type required default
name Name used for Cloud Run service. string
project_id Project id used for all resources. string
region Region used for all resources. string
containers Containers in name => attributes format. map(object({…})) {}
context Context-specific interpolations. object({…}) {}
deletion_protection Deletion protection setting for this Cloud Run service. string null
encryption_key The full resource name of the Cloud KMS CryptoKey. string null
iam IAM bindings for Cloud Run service in {ROLE => [MEMBERS]} format. map(list(string)) {}
job_config Cloud Run Job specific configuration. object({…}) {}
labels Resource labels. map(string) {}
launch_stage The launch stage as defined by Google Cloud Platform Launch Stages. string null
managed_revision Whether the Terraform module should control the deployment of revisions. bool true
revision Revision template configurations. object({…}) {}
service_account_config Service account configurations. object({…}) {}
service_config Cloud Run service specific configuration options. object({…}) {}
tag_bindings Tag bindings for this service, in key => tag value id format. map(string) {}
type Type of Cloud Run resource to deploy: JOB, SERVICE or WORKERPOOL. string "SERVICE"
volumes Named volumes in containers in name => attributes format. map(object({…})) {}
vpc_connector_create VPC connector network configuration. Must be provided if new VPC connector is being created. object({…}) null
workerpool_config Cloud Run Worker Pool specific configuration. object({…}) {}

Outputs

name description sensitive
id Fully qualified job or service id.
invoke_command Command to invoke Cloud Run Service / submit job.
job Cloud Run Job.
resource Cloud Run resource (job, service or worker_pool).
resource_name Cloud Run resource (job, service or workerpool) service name.
service Cloud Run Service.
service_account Service account resource.
service_account_email Service account email.
service_account_iam_email Service account email.
service_name Cloud Run service name.
service_uri Main URI in which the service is serving traffic.
vpc_connector VPC connector resource if created.

Fixtures