# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: blueprints.cloud.google.com/v1alpha1
kind: BlueprintMetadata
metadata:
  name: terraform-google-cloud-run-v-2
  annotations:
    config.kubernetes.io/local-config: "true"
spec:
  info:
    title: Cloud Run v2 Service
    source:
      repo: https://github.com/GoogleCloudPlatform/terraform-google-cloud-run.git
      sourceType: git
      dir: /modules/v2
    version: 0.17.2
    actuationTool:
      flavor: Terraform
      version: ">= 1.3"
    description: {}
  content:
    examples:
      - name: cloud_run_vpc_connector
        location: examples/cloud_run_vpc_connector
      - name: secure_cloud_run
        location: examples/secure_cloud_run
      - name: secure_cloud_run_standalone
        location: examples/secure_cloud_run_standalone
      - name: simple_cloud_run
        location: examples/simple_cloud_run
      - name: simple_cloud_run_with_cmek
        location: examples/simple_cloud_run_with_cmek
      - name: simple_job_exec
        location: examples/simple_job_exec
      - name: v2
        location: examples/v2
      - name: v2_with_gmp
        location: examples/v2_with_gmp
  interfaces:
    variables:
      - name: project_id
        description: The project ID to deploy to
        varType: string
        required: true
      - name: location
        description: Cloud Run service deployment location
        varType: string
        required: true
      - name: service_name
        description: The name of the Cloud Run service to create
        varType: string
        required: true
      - name: description
        description: Cloud Run service description. This field currently has a 512-character limit.
        varType: string
      - name: containers
        description: Map of container images for the service
        varType: |-
          list(object({
              container_name       = optional(string, null)
              container_image      = string
              working_dir          = optional(string, null)
              depends_on_container = optional(list(string), null)
              container_args       = optional(list(string), null)
              container_command    = optional(list(string), null)
              env_vars             = optional(map(string), {})
              env_secret_vars = optional(map(object({
                secret  = string
                version = string
              })), {})
              volume_mounts = optional(list(object({
                name       = string
                mount_path = string
              })), [])
              ports = optional(object({
                name           = optional(string, "http1")
                container_port = optional(number, 8080)
              }), {})
              resources = optional(object({
                limits = optional(object({
                  cpu    = optional(string)
                  memory = optional(string)
                }))
                cpu_idle          = optional(bool, true)
                startup_cpu_boost = optional(bool, false)
              }), {})
              startup_probe = optional(object({
                failure_threshold     = optional(number, null)
                initial_delay_seconds = optional(number, null)
                timeout_seconds       = optional(number, null)
                period_seconds        = optional(number, null)
                http_get = optional(object({
                  path = optional(string)
                  port = optional(string)
                  http_headers = optional(list(object({
                    name  = string
                    value = string
                  })), [])
                }), null)
                tcp_socket = optional(object({
                  port = optional(number)
                }), null)
                grpc = optional(object({
                  port    = optional(number)
                  service = optional(string)
                }), null)
              }), null)
              liveness_probe = optional(object({
                failure_threshold     = optional(number, null)
                initial_delay_seconds = optional(number, null)
                timeout_seconds       = optional(number, null)
                period_seconds        = optional(number, null)
                http_get = optional(object({
                  path = optional(string)
                  port = optional(string)
                  http_headers = optional(list(object({
                    name  = string
                    value = string
                  })), null)
                }), null)
                tcp_socket = optional(object({
                  port = optional(number)
                }), null)
                grpc = optional(object({
                  port    = optional(number)
                  service = optional(string)
                }), null)
              }), null)
            }))
        required: true
        connections:
          - source:
              source: github.com/terraform-google-modules/terraform-google-memorystore
              version: ">= 12.0"
            spec:
              outputExpr: "{\"REDIS_HOST\": host, \"REDIS_PORT\": env_vars.REDIS_PORT, \"REDIS_AUTH_STRING\": auth_string}"
              inputPath: env_vars
          - source:
              source: github.com/terraform-google-modules/terraform-google-sql-db//modules/postgresql
              version: ">= 23.0"
            spec:
              outputExpr: "{\"CLOUD_SQL_DATABASE_HOST\" : instance_first_ip_address, \"CLOUD_SQL_DATABASE_CONNECTION_NAME\" : instance_connection_name, \"CLOUD_SQL_DATABASE_NAME\" : env_vars.CLOUD_SQL_DATABASE_NAME}"
              inputPath: env_vars
          - source:
              source: github.com/terraform-google-modules/terraform-google-sql-db//modules/mysql
              version: ">= 23.0"
            spec:
              outputExpr: "{\"CLOUD_SQL_DATABASE_HOST\" : instance_first_ip_address, \"CLOUD_SQL_DATABASE_CONNECTION_NAME\" : instance_connection_name, \"CLOUD_SQL_DATABASE_NAME\" : env_vars.CLOUD_SQL_DATABASE_NAME}"
              inputPath: env_vars
          - source:
              source: github.com/terraform-google-modules/terraform-google-service-accounts//modules/simple-sa
              version: ">= 4.4"
            spec:
              outputExpr: "{\"SERVICE_ACCOUNT_EMAIL\" : email, \"SERVICE_ACCOUNT_IAM_EMAIL\" : iam_email}"
              inputPath: env_vars
          - source:
              source: github.com/GoogleCloudPlatform/terraform-google-cloud-run//modules/v2
              version: ">= 0.13"
            spec:
              outputExpr: "{\"SERVICE_ENDPOINT\": service_uri}"
              inputPath: env_vars
          - source:
              source: github.com/terraform-google-modules/terraform-google-pubsub
              version: ">= 7.0.0"
            spec:
              outputExpr: "{\"TOPIC_ID\": id}"
              inputPath: env_vars
          - source:
              source: github.com/GoogleCloudPlatform/terraform-google-secret-manager//modules/simple-secret
              version: ">= 0.5.1"
            spec:
              outputExpr: "{\"SECRET\": env_vars.SECRET }"
              inputPath: env_secret_vars
          - source:
              source: github.com/GoogleCloudPlatform/terraform-google-cloud-spanner
              version: ">= 1.1.1"
            spec:
              outputExpr: env_vars
              inputPath: env_vars
          - source:
              source: github.com/terraform-google-modules/terraform-google-bigquery
              version: ^10.0
            spec:
              outputExpr: "{\"BIGQUERY_DATASET\" : env_vars.BIGQUERY_DATASET, \"BIGQUERY_TABLES\" : env_vars.BIGQUERY_TABLES, \"BIGQUERY_VIEWS\" : env_vars.BIGQUERY_VIEWS, \"BIGQUERY_MATERIALIZED_VIEWS\" : env_vars.BIGQUERY_MATERIALIZED_VIEWS, \"BIGQUERY_EXTERNAL_TABLES\" : env_vars.BIGQUERY_EXTERNAL_TABLES, \"BIGQUERY_ROUTINES\" : env_vars.BIGQUERY_ROUTINES}"
              inputPath: env_vars
          - source:
              source: github.com/GoogleCloudPlatform/terraform-google-bigtable
              version: ">= 0.1.0"
            spec:
              outputExpr: "{\"BIGTABLE_INSTANCE_ID\" : instance_id, \"BIGTABLE_TABLE_ID\" : table_ids[0]}"
              inputPath: env_vars
          - source:
              source: github.com/GoogleCloudPlatform/terraform-google-regional-lb-http//modules/frontend
              version: ">= 0.4.0"
            spec:
              outputExpr: "{\"IP_ADDRESS_HTTP\": ip_address_http, \"IP_ADDRESS_HTTPS\": ip_address_https}"
              inputPath: env_vars
      - name: create_service_account
        description: Create a new service account for cloud run service
        varType: bool
        defaultValue: true
      - name: service_account_project_roles
        description: Roles to grant to the newly created cloud run SA in specified project. Should be used with create_service_account set to true and no input for service_account
        varType: list(string)
        defaultValue: []
        connections:
          - source:
              source: github.com/GoogleCloudPlatform/terraform-google-secret-manager//modules/simple-secret
              version: ">= 0.5.1"
            spec:
              outputExpr: "[\"roles/secretmanager.secretAccessor\"]"
          - source:
              source: github.com/terraform-google-modules/terraform-google-sql-db//modules/postgresql
              version: ">= 23.0"
            spec:
              outputExpr: "[\"roles/cloudsql.instanceUser\", \"roles/cloudsql.client\"]"
          - source:
              source: github.com/terraform-google-modules/terraform-google-sql-db//modules/mysql
              version: ">= 23.0"
            spec:
              outputExpr: "[\"roles/cloudsql.instanceUser\", \"roles/cloudsql.client\"]"
          - source:
              source: github.com/terraform-google-modules/terraform-google-memorystore
              version: ">= 12.0"
            spec:
              outputExpr: "[\"roles/redis.editor\"]"
          - source:
              source: github.com/GoogleCloudPlatform/terraform-google-cloud-run//modules/v2
              version: ">= 0.13"
            spec:
              outputExpr: "[\"roles/run.invoker\"]"
          - source:
              source: github.com/terraform-google-modules/terraform-google-project-factory//modules/project_services
              version: ">= 17.1.0"
            spec:
              outputExpr: "[\"roles/aiplatform.user\"]"
          - source:
              source: github.com/terraform-google-modules/terraform-google-pubsub
              version: ">= 7.0.0"
            spec:
              outputExpr: "[\"roles/pubsub.publisher\", \"roles/pubsub.subscriber\", \"roles/run.invoker\"]"
          - source:
              source: github.com/GoogleCloudPlatform/terraform-google-cloud-spanner
              version: ">= 1.1.1"
            spec:
              outputExpr: "[\"roles/spanner.databaseAdmin\"]"
          - source:
              source: github.com/terraform-google-modules/terraform-google-bigquery
              version: ^10.0
            spec:
              outputExpr: "[\"roles/bigquery.dataEditor\"]"
          - source:
              source: github.com/GoogleCloudPlatform/terraform-google-bigtable
              version: ">= 0.1.0"
            spec:
              outputExpr: "[\"roles/bigtable.admin\"]"
      - name: members
        description: "Users/SAs to be given invoker access to the service. Grant invoker access by specifying the users or service accounts (SAs). Use allUsers for public access, allAuthenticatedUsers for access by logged-in Google users, or provide a list of specific users/SAs. See the complete list of available options: https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/cloud_run_v2_service_iam#member\\/members-1"
        varType: list(string)
        defaultValue: []
      - name: vpc_access
        description: VPC Access configuration to use for this Task. For more information, visit https://cloud.google.com/run/docs/configuring/connecting-vpc
        varType: |-
          object({
              connector = optional(string)
              egress    = optional(string)
              network_interfaces = optional(object({
                network    = optional(string)
                subnetwork = optional(string)
                tags       = optional(list(string))
              }))
            })
        connections:
          - source:
              source: github.com/terraform-google-modules/terraform-google-network//modules/vpc-serverless-connector-beta
              version: ">= 9.1"
            spec:
              outputExpr: connector_ids
              inputPath: connector
      - name: cloud_run_deletion_protection
        description: This field prevents Terraform from destroying or recreating the Cloud Run v2 Jobs and Services
        varType: bool
        defaultValue: true
      - name: enable_prometheus_sidecar
        description: Enable Prometheus sidecar in Cloud Run instance.
        varType: bool
        defaultValue: false
      - name: volumes
        description: Volumes needed for environment variables (when using secret)
        varType: |-
          list(object({
              name = string
              secret = optional(object({
                secret       = string
                default_mode = optional(string)
                items = optional(object({
                  path    = string
                  version = optional(string)
                  mode    = optional(string)
                }))
              }))
              cloud_sql_instance = optional(object({
                instances = optional(list(string))
              }))
              empty_dir = optional(object({
                medium     = optional(string)
                size_limit = optional(string)
              }))
              gcs = optional(object({
                bucket    = string
                read_only = optional(string)
              }))
              nfs = optional(object({
                server    = string
                path      = string
                read_only = optional(string)
              }))
            }))
        defaultValue: []
        connections:
          - source:
              source: github.com/terraform-google-modules/terraform-google-sql-db//modules/postgresql
              version: ">= 23.0"
            spec:
              outputExpr: instance_connection_name
              inputPath: cloud_sql_instance.instances
          - source:
              source: github.com/terraform-google-modules/terraform-google-sql-db//modules/mysql
              version: ">= 23.0"
            spec:
              outputExpr: instance_connection_name
              inputPath: cloud_sql_instance.instances
          - source:
              source: github.com/terraform-google-modules/terraform-google-cloud-storage//modules/simple_bucket
              version: ">= 8.0"
            spec:
              outputExpr: name
              inputPath: gcs.bucket
      - name: traffic
        description: Specifies how to distribute traffic over a collection of Revisions belonging to the Service. If traffic is empty or not provided, defaults to 100% traffic to the latest Ready Revision.
        varType: |-
          list(object({
              type     = optional(string, "TRAFFIC_TARGET_ALLOCATION_TYPE_LATEST")
              percent  = optional(number, 100)
              revision = optional(string, null)
              tag      = optional(string, null)
            }))
        defaultValue: []
      - name: service_scaling
        description: Scaling settings that apply to the whole service
        varType: |-
          object({
              min_instance_count = optional(number)
            })
      - name: service_labels
        description: Unstructured key value map that can be used to organize and categorize objects. For more information, visit https://cloud.google.com/resource-manager/docs/creating-managing-labels or https://cloud.google.com/run/docs/configuring/labels
        varType: map(string)
        defaultValue: {}
        connections:
          - source:
              source: github.com/terraform-google-modules/terraform-google-project-factory//modules/project_services
              version: ">= 17.1.0"
            spec:
              outputExpr: "{\"vertex-ai\": \"true\"}"
      - name: service_annotations
        description: Unstructured key value map that may be set by external tools to store and arbitrary metadata. They are not queryable and should be preserved when modifying objects. Refer https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/cloud_run_v2_service#annotations
        varType: map(string)
        defaultValue: {}
      - name: client
        description: Arbitrary identifier for the API client and version identifier
        varType: |-
          object({
              name    = optional(string, null)
              version = optional(string, null)
            })
        defaultValue: {}
      - name: ingress
        description: Provides the ingress settings for this Service. On output, returns the currently observed ingress settings, or INGRESS_TRAFFIC_UNSPECIFIED if no revision is active.
        varType: string
        defaultValue: INGRESS_TRAFFIC_ALL
      - name: launch_stage
        description: The launch stage as defined by Google Cloud Platform Launch Stages. Cloud Run supports ALPHA, BETA, and GA. If no value is specified, GA is assumed.
        varType: string
        defaultValue: GA
      - name: custom_audiences
        description: One or more custom audiences that you want this service to support. Specify each custom audience as the full URL in a string. Refer https://cloud.google.com/run/docs/configuring/custom-audiences
        varType: list(string)
      - name: binary_authorization
        description: Settings for the Binary Authorization feature.
        varType: |-
          object({
              breakglass_justification = optional(bool) # If present, indicates to use Breakglass using this justification. If useDefault is False, then it must be empty. For more information on breakglass, see https://cloud.google.com/binary-authorization/docs/using-breakglass
              use_default              = optional(bool) #If True, indicates to use the default project's binary authorization policy. If False, binary authorization will be disabled.
            })
      - name: revision
        description: The unique name for the revision. If this field is omitted, it will be automatically generated based on the Service name
        varType: string
      - name: template_scaling
        description: Scaling settings for this Revision.
        varType: |-
          object({
              min_instance_count = optional(number)
              max_instance_count = optional(number)
            })
      - name: template_labels
        description: Unstructured key value map that can be used to organize and categorize objects. For more information, visit https://cloud.google.com/resource-manager/docs/creating-managing-labels or https://cloud.google.com/run/docs/configuring/labels
        varType: map(string)
        defaultValue: {}
      - name: template_annotations
        description: Unstructured key value map that may be set by external tools to store and arbitrary metadata. They are not queryable and should be preserved when modifying objects. Refer https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/cloud_run_v2_service#annotations
        varType: map(string)
        defaultValue: {}
      - name: timeout
        description: Max allowed time for an instance to respond to a request. A duration in seconds with up to nine fractional digits, ending with 's'
        varType: string
      - name: service_account
        description: Email address of the IAM service account associated with the revision of the service
        varType: string
        connections:
          - source:
              source: github.com/terraform-google-modules/terraform-google-service-accounts//modules/simple-sa
              version: ">= 4.4"
            spec:
              outputExpr: email
      - name: encryption_key
        description: A reference to a customer managed encryption key (CMEK) to use to encrypt this container image. This is optional.
        varType: string
      - name: max_instance_request_concurrency
        description: Sets the maximum number of requests that each serving instance can receive. This is optional.
        varType: string
      - name: session_affinity
        description: Enables session affinity. For more information, go to https://cloud.google.com/run/docs/configuring/session-affinity
        varType: string
      - name: execution_environment
        description: The sandbox environment to host this Revision.
        varType: string
        defaultValue: EXECUTION_ENVIRONMENT_GEN2
    outputs:
      - name: apphub_service_uri
        description: Service URI in CAIS style to be used by Apphub.
        type:
          - object
          - location: string
            service_id: string
            service_uri: string
      - name: creator
        description: Email address of the authenticated creator.
        type: string
      - name: effective_annotations
        description: All of annotations (key/value pairs) present on the resource in GCP, including the annotations configured through Terraform, other clients and services.
        type:
          - map
          - string
      - name: last_modifier
        description: Email address of the last authenticated modifier.
        type: string
      - name: latest_created_revision
        description: Name of the last created revision. See comments in reconciling for additional information on reconciliation process in Cloud Run.
        type: string
      - name: latest_ready_revision
        description: Name of the latest revision that is serving traffic. See comments in reconciling for additional information on reconciliation process in Cloud Run.
        type: string
      - name: location
        description: Location in which the Cloud Run service was created
        type: string
      - name: observed_generation
        description: The generation of this Service currently serving traffic.
        type: string
      - name: project_id
        description: Google Cloud project in which the service was created
        type: string
      - name: service_account_id
        description: Service account id and email
        type:
          - object
          - email: string
            id: string
            member: string
      - name: service_id
        description: Unique Identifier for the created service with format projects/{{project}}/locations/{{location}}/services/{{name}}
        type: string
      - name: service_name
        description: Name of the created service
        type: string
      - name: service_uri
        description: The main URI in which this Service is serving traffic.
        type: string
      - name: traffic_statuses
        description: Detailed status information for corresponding traffic targets.
        type:
          - list
          - - object
            - percent: number
              revision: string
              tag: string
              type: string
              uri: string
  requirements:
    roles:
      - level: Project
        roles:
          - roles/accesscontextmanager.policyAdmin
          - roles/orgpolicy.policyAdmin
      - level: Project
        roles:
          - roles/resourcemanager.folderAdmin
          - roles/resourcemanager.projectCreator
          - roles/resourcemanager.projectDeleter
      - level: Project
        roles:
          - roles/run.admin
          - roles/iam.serviceAccountAdmin
          - roles/artifactregistry.admin
          - roles/iam.serviceAccountUser
          - roles/serviceusage.serviceUsageViewer
          - roles/cloudkms.admin
          - roles/resourcemanager.projectIamAdmin
    services:
      - cloudresourcemanager.googleapis.com
      - storage-api.googleapis.com
      - serviceusage.googleapis.com
      - run.googleapis.com
      - cloudkms.googleapis.com
      - iam.googleapis.com
      - accesscontextmanager.googleapis.com
      - cloudbilling.googleapis.com
      - monitoring.googleapis.com
      - compute.googleapis.com
    providerVersions:
      - source: hashicorp/google
        version: ">= 6, < 7"
      - source: hashicorp/google-beta
        version: ">= 6, < 7"
