Terraform Google Cloud Run Module

repository·main·Indexed 42 days ago

https://github.com/googlecloudplatform/terraform-google-cloud-run

A Terraform module for deploying containerized applications on Google Cloud Run. It supports automated domain mapping, IAM invoker configuration, Serverless VPC Connectors, Customer-Managed Encryption Keys (CMEK), and hardened environments featuring VPC Service Controls, Cloud Armor, and Load Balancing.

Tokens
20.6K
Snippets
32
Records
74
Agent score
53%

What's inside Terraform Google Cloud Run

  1. Understand the security and networking resources created by Secure Cloud Run

    main

    The module manages resources across multiple projects based on your configuration:

    Networking (secure-serverless-net)

    • VPC Project: Creates Firewall rules (Serverless to VPC, VPC to Serverless, VPC to LB, and Health Checks) and a subnetwork for the VPC Connector.
    • VPC or Serverless Project: Creates the Serverless VPC Connector.
    • IAM: Grants roles/networkUser to Cloud Services service accounts and roles/vpcaccess.user to the Cloud Run Service Identity.

    Security (secure-cloud-run-security)

    • KMS Project: Creates KMS Keyring and Key for Customer Managed Encryption Keys (CMEK).
    • Serverless Project: Enables Cloud Run related Organization Policies, restricts Ingress to 'internal and Cloud Load Balancing', and restricts VPC Egress to 'Private Ranges Only'.
    • IAM Roles: If group emails are provided, it grants roles for:
      • Serverless Administrator (Service Project): roles/run.admin, roles/compute.networkViewer, roles/compute.networkUser.
      • Serverless Security Administrator (Security Project): roles/run.viewer, roles/cloudkms.viewer, roles/artifactregistry.reader.
      • Cloud Run Developer (Security Project): roles/run.developer, roles/artifactregistry.writer, roles/cloudkms.cryptoKeyEncrypter.
      • Cloud Run User (Security Project): roles/run.invoker.

    Core Infrastructure (secure-cloud-run-core)

    • Creates the Cloud Run Service.
    • Creates a Load Balancer with Google-managed SSL certificates.
    • Creates a Cloud Armor Service with pre-configured rules for: SQLi, XSS, LFI, RCE, RFI, Scannerdetection, Protocolattack, and Sessionfixation.
  2. Configure SSL certificate mode for Cloud Run custom domains

    main

    When mapping a custom domain to Cloud Run using the secure-cloud-run-core module, you can control how SSL certificates are managed via the certificate_mode variable.

    To ensure Google Cloud Platform (GCP) automatically manages the SSL certificate for your custom domain, set the certificate_mode to AUTOMATIC.

    Important Requirement: For GCP to successfully manage the SSL certificate, you must add the Service Account used by the module as a Domain verified owner in the Google Search Console.

    # Example configuration for automatic certificate management
    module "secure-cloud-run-core" {
      # ... other configuration ...
      certificate_mode = "AUTOMATIC"
    }
  3. Requirements for the Simple Cloud Run example

    main

    Before running this example, ensure the following software, permissions, and APIs are available:

    Software

    Service Account Permissions

    The executing service account requires the following role:

    • roles/run.admin (Cloud Run Admin)

    You can use the Project Factory module and the IAM module to provision a service account with these roles.

    Required APIs

    The following API must be enabled in your GCP project:

    • run.googleapis.com (Google Cloud Run)
  4. Migrate from v0.13.0 to v0.14.0 (Cloud Run v2)

    main
    Upgrading from version 0.13.0 to 0.14.0 is a backward-incompatible change. This release introduces new deletion_protection and deletion_policy settings to align with the Google Cloud Provider v6.0.0 behavior. By default, several resources now have protection enabled to prevent accidental deletion. If you require the previous behavior (allowing deletion), you must explicitly set the protection flags to false or the policy to "DELETE" in your module configurations.
  5. Use the Secure Cloud Run Security module

    main

    The secure-cloud-run-security module automates basic deployment security configurations for Cloud Run. It manages Customer Managed Encryption Keys (CMEK) in a KMS project and enforces Organization Policies in a Serverless project.

    Key actions performed by the module:

    • CMEK Setup: Creates a KMS Keyring and Key in the specified KMS Project.
    • Organization Policies: Enables policies in the Serverless Project to:
      • Allow Ingress only from internal and Cloud Load Balancing.
      • Allow VPC Egress to Private Ranges Only.
    • IAM Role Assignment: If groups are provided, it assigns specific roles to the following personas:
      • Serverless Administrator (Service Project): roles/run.admin, roles/compute.networkViewer, compute.networkUser.
      • Serverless Security Administrator (Security Project): roles/run.viewer, roles/cloudkms.viewer, roles/artifactregistry.reader.
      • Cloud Run Developer (Security Project): roles/run.developer, roles/artifactregistry.writer, roles/cloudkms.cryptoKeyEncrypter.
      • Cloud Run User (Service Project): roles/run.invoker.
    module "cloud_run_security" {
      source = "../secure-cloud-run-security"
    
      kms_project_id        = <KMS PROJECT ID>
      location              = <KMS LOCATION>
      serverless_project_id = <SERVERLESS PROJECT ID>
      key_name              = <KEY NAME>
      keyring_name          = <KEYRING NAME>
      key_rotation_period   = <KEY ROTATION PERIOD>
      key_protection_level  = <KEY PROTECTION LEVEL>
    
      encrypters = [
        "serviceAccount:<SERVERLESS IDENTITY EMAIL>",
        "serviceAccount:<CLOUD RUN SERVICE ACCOUNT>"
      ]
    
      decrypters = [
        "serviceAccount:<SERVERLESS IDENTITY EMAIL>",
        "serviceAccount:<CLOUD RUN SERVICE ACCOUNT>"
      ]
    }
  6. Deploy the Secure Cloud Run Example

    main

    This example demonstrates how to deploy a secure Cloud Run environment including domain mapping, IAM policies, VPC connectivity, and Cloud Armor protection.

    Deployment Steps

    1. Prepare the configuration file:
      mv terraform.example.tfvars terraform.tfvars
    2. Update terraform.tfvars with your specific environment values.
    3. Initialize Terraform:
      terraform init
    4. Review the execution plan:
      terraform plan
    5. Apply the infrastructure:
      terraform apply

    Cleanup

    To remove all resources created by this example, run:

    terraform destroy
    # Deployment sequence
    mv terraform.example.tfvars terraform.tfvars
    terraform init
    terraform plan
    terraform apply
    
    # Cleanup
    terraform destroy
  7. Provisioning permissions for Secure Cloud Run

    main

    To provision the resources in this module, the executing service account must have the following roles assigned in the respective projects:

    VPC Project

    • roles/compute.xpnAdmin (Compute Shared VPC Admin)
    • roles/compute.networkAdmin (Network Admin)
    • roles/compute.securityAdmin (Security Admin)
    • roles/vpcaccess.admin (Serverless VPC Access Admin)

    KMS Project

    • roles/cloudkms.admin (Cloud KMS Admin)

    Serverless Project

    • roles/compute.securityAdmin (Security Admin)
    • roles/vpcaccess.admin (Serverless VPC Access Admin)
    • roles/run.developer (Cloud Run Developer)
    • roles/compute.networkUser (Compute Network User)
    • roles/artifactregistry.reader (Artifact Registry Reader)

    Important: You must manually grant the roles/secretmanager.secretAccessor role to the Cloud Run service account to allow it to read secrets from Secret Manager.

  8. Requirements for Secure Serverless deployment on Foundation v2.3.1

    main

    To use this customization guide, ensure the following prerequisites are met:

    1. Foundation Deployment: terraform-example-foundation version 2.3.1 must be deployed up to at least step 4-projects.
    2. Permissions: You must have the Service Account User role (roles/iam.serviceAccountUser) assigned to the Terraform Service Account located in the foundation Seed Project.

    Terraform Service Account Format: org-terraform@<SEED_PROJECT_ID>.iam.gserviceaccount.com

  9. Migrate secure-serverless-net to v7.0

    main

    When upgrading to v7.0, the secure-cloud-serverless-net module has been renamed to secure-serverless-net. Additionally, a new required variable serverless_type must be provided to specify the service type (e.g., "CLOUD_RUN"), which enables support for Cloud Functions (2nd Gen).

    module "cloud_run_network" {
      # Renamed source
      source = "../secure-serverless-net"
    
      connector_name            = var.connector_name
      subnet_name               = var.subnet_name
      location                  = var.location
      vpc_project_id            = var.vpc_project_id
      serverless_project_id     = var.serverless_project_id
      shared_vpc_name           = var.shared_vpc_name
      connector_on_host_project = false
      ip_cidr_range             = var.ip_cidr_range
      create_subnet             = var.create_subnet
      resource_names_suffix     = var.resource_names_suffix
      
      # New required variable
      serverless_type           = "CLOUD_RUN"
      
      serverless_service_identity_email = google_project_service_identity.serverless_sa.email
    }
  10. Deploy a secure Cloud Run environment

    main

    The secure-cloud-run module automates the deployment of a secure Cloud Run service by orchestrating three sub-modules: secure-cloud-run-core, secure-serverless-net, and secure-cloud-run-security.

    It handles networking (VPC Connectors, Firewall rules), security (CMEK via KMS, Organization Policies, Cloud Armor, and IAM roles), and core infrastructure (Cloud Run service and Load Balancer with Google-managed SSL).

    module "secure_cloud_run" {
      source = "../modules/secure-cloud-run"
    
      vpc_project_id                          = <VPC Project ID>
      kms_project_id                          = <KMS Project ID>
      serverless_project_id                   = <Serverless Project ID>
      domain                                  = <Domain>
      shared_vpc_name                         = <Shared VPC Name>
      ip_cidr_range                           = <IP CIDR Range>
      service_name                            = <Service Name>
      location                                = <Location>
      region                                  = <Region>
      image                                   = <Image>
      cloud_run_sa                            = <Cloud Run Service Account>
      artifact_registry_repository_location   = <Artifact Registry Repository Location>
      artifact_registry_repository_name       = <Artifact Registry Repository Name>
      artifact_registry_repository_project_id = <Artifact Registry Repository Project ID>
    }
  11. Migrate from cloud-run/v2 v0.12.0 to v0.13.0

    main

    The release of cloud-run/v2 v0.13.0 introduced a backward-incompatible change regarding service account identity.

    In v0.12.0, if no service account was provided, the module defaulted to using the project's default compute service account (<project-num>-compute@developer.gserviceaccount.com).

    In v0.13.0, if no service account is provided, the module now creates a new service account by default.

    To maintain the previous behavior (using the default compute service account instead of creating a new one), you must explicitly set create_service_account = false in your module configuration.

    module "cloud_run_v2" {
      source  = "GoogleCloudPlatform/cloud-run/google//modules/v2"
      version = "~> 0.13"
    
      service_name = "cloud-run-v2"
      project_id   = var.project_id
      location     = "us-central1"
      containers = [
        {
          container_image = "us-docker.pkg.dev/cloudrun/container/hello"
          container_name  = "hello-world"
        }
      ]
      # Set to false to use the default compute service account instead of creating a new one
      create_service_account = false
    }