Mengamankan layanan Cloud Run

Buat dua layanan; satu frontend publik, satu lagi backend yang aman. Menggunakan kebijakan IAM untuk mengonfigurasi akses.

Contoh kode

Terraform

Untuk mempelajari cara menerapkan atau menghapus konfigurasi Terraform, lihat Perintah dasar Terraform. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi penyedia Terraform.

resource "google_cloud_run_v2_service" "renderer" {
  name     = "renderer"
  location = "us-central1"

  deletion_protection = false # set to "true" in production

  template {
    containers {
      # Replace with the URL of your Secure Services > Renderer image.
      #   gcr.io/<PROJECT_ID>/renderer
      image = "us-docker.pkg.dev/cloudrun/container/hello"
    }
    service_account = google_service_account.renderer.email
  }
}

resource "google_cloud_run_v2_service" "editor" {
  name     = "editor"
  location = "us-central1"

  deletion_protection = false # set to "true" in production

  template {
    containers {
      # Replace with the URL of your Secure Services > Editor image.
      #   gcr.io/<PROJECT_ID>/editor
      image = "us-docker.pkg.dev/cloudrun/container/hello"
      env {
        name  = "EDITOR_UPSTREAM_RENDER_URL"
        value = google_cloud_run_v2_service.renderer.uri
      }
    }
    service_account = google_service_account.editor.email

  }
}

resource "google_service_account" "renderer" {
  account_id   = "renderer-identity"
  display_name = "Service identity of the Renderer (Backend) service."
}

resource "google_service_account" "editor" {
  account_id   = "editor-identity"
  display_name = "Service identity of the Editor (Frontend) service."
}

resource "google_cloud_run_service_iam_member" "editor_invokes_renderer" {
  location = google_cloud_run_v2_service.renderer.location
  service  = google_cloud_run_v2_service.renderer.name
  role     = "roles/run.invoker"
  member   = "serviceAccount:${google_service_account.editor.email}"
}

data "google_iam_policy" "noauth" {
  binding {
    role = "roles/run.invoker"
    members = [
      "allUsers",
    ]
  }
}

resource "google_cloud_run_service_iam_policy" "noauth" {
  location = google_cloud_run_v2_service.editor.location
  project  = google_cloud_run_v2_service.editor.project
  service  = google_cloud_run_v2_service.editor.name

  policy_data = data.google_iam_policy.noauth.policy_data
}

output "backend_url" {
  value = google_cloud_run_v2_service.renderer.uri
}

output "frontend_url" {
  value = google_cloud_run_v2_service.editor.uri
}

Langkah selanjutnya

Untuk menelusuri dan memfilter contoh kode untuk produk Google Cloud lainnya, lihat browser contoh Google Cloud.