配置 VPC 访问

使用 Terraform 将 Cloud Run 服务配置为使用 VPC 访问通道连接器

代码示例

Terraform

如需了解如何应用或移除 Terraform 配置,请参阅基本 Terraform 命令。 如需了解详情,请参阅 Terraform 提供程序参考文档

resource "google_project_service" "vpcaccess_api" {
  service            = "vpcaccess.googleapis.com"
  disable_on_destroy = false
}

# VPC
resource "google_compute_network" "default" {
  name                    = "cloudrun-network"
  auto_create_subnetworks = false
}

# VPC access connector
resource "google_vpc_access_connector" "connector" {
  name          = "vpcconn"
  region        = "us-west1"
  ip_cidr_range = "10.8.0.0/28"
  network       = google_compute_network.default.name
  depends_on    = [google_project_service.vpcaccess_api]
  min_instances = 2
  max_instances = 3
}

# Cloud Router
resource "google_compute_router" "router" {
  name    = "router"
  region  = "us-west1"
  network = google_compute_network.default.id
}

# NAT configuration
resource "google_compute_router_nat" "router_nat" {
  name                               = "nat"
  region                             = "us-west1"
  router                             = google_compute_router.router.name
  source_subnetwork_ip_ranges_to_nat = "ALL_SUBNETWORKS_ALL_IP_RANGES"
  nat_ip_allocate_option             = "AUTO_ONLY"
}

# Cloud Run service
resource "google_cloud_run_v2_service" "gcr_service" {
  name     = "mygcrservice"
  location = "us-west1"

  deletion_protection = false # set to "true" in production

  template {
    containers {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
      resources {
        limits = {
          cpu    = "1000m"
          memory = "512Mi"
        }
      }
      # the service uses this SA to call other Google Cloud APIs
      # service_account_name = myservice_runtime_sa
    }

    scaling {
      # Limit scale up to prevent any cost blow outs!
      max_instance_count = 5
    }

    vpc_access {
      # Use the VPC Connector
      connector = google_vpc_access_connector.connector.id
      # all egress from the service should go through the VPC Connector
      egress = "ALL_TRAFFIC"
    }
  }
}

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器