1

我正在尝试使用以下Terraform代码在Cloud Run上运行 docker 映像:

provider "google" {
  credentials = file("myCredentials.json")
  project     = "myproject-214771"
  region      = "asia-northeast1"
}

resource "google_cloud_run_service" "default" {
  name     = "hello-world"
  location = "asia-northeast1"

  template {
    spec {
      containers {
        image = "gcr.io/myproject-214771/hello-world:latest"
      }
    }
  }

  traffic {
    percent         = 100
    latest_revision = true
  }
}

然后,运行docker镜像就成功了:

在此处输入图像描述

但是当我访问 URL 时,它会显示:

在此处输入图像描述

错误:禁止您的客户端无权从该服务器获取 URL /

我的Terraform代码中是否有任何错误?

4

1 回答 1

1

将此代码添加(复制并粘贴)到您的Terraform代码中,以允许对公共 API 或网站进行未经身份验证的调用

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

resource "google_cloud_run_service_iam_policy" "noauth" {
  location    = google_cloud_run_service.default.location
  project     = google_cloud_run_service.default.project
  service     = google_cloud_run_service.default.name

  policy_data = data.google_iam_policy.noauth.policy_data
}

所以这是完整的代码

provider "google" {
  credentials = file("myCredentials.json")
  project     = "myproject-214771"
  region      = "asia-northeast1"
}

resource "google_cloud_run_service" "default" {
  name     = "hello-world"
  location = "asia-northeast1"

  template {
    spec {
      containers {
        image = "gcr.io/myproject-214771/hello-world:latest"
      }
    }
  }

  traffic {
    percent         = 100
    latest_revision = true
  }
}

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

resource "google_cloud_run_service_iam_policy" "noauth" {
  location    = google_cloud_run_service.default.location
  project     = google_cloud_run_service.default.project
  service     = google_cloud_run_service.default.name

  policy_data = data.google_iam_policy.noauth.policy_data
}

最后,您的 URL 可以正确显示您的网站:

在此处输入图像描述

此外,现在“身份验证”“允许未经身份验证”

在此处输入图像描述

不要忘记将角色“Cloud Run Admin”添加到您的服务帐户

在此处输入图像描述

否则,您不能允许对公共 API 或网站进行未经身份验证的调用,那么您将在下面收到此错误:

为 cloudrun 服务“v1/projects/myproject-214771/locations/asia-northeast1/services/hello-world”设置 IAM 策略时出错:googleapi:错误 403:资源 'projects/myproject- 上的权限'run.services.setIamPolicy'被拒绝214771/locations/asia-northeast1/services/hello-world'(或资源可能不存在)。

此外,使用以下这些角色,您不能允许对公共 API 或网站进行未经身份验证的调用

在此处输入图像描述

只有角色“Cloud Run Admin”才能允许对公共 API 或网站进行未经身份验证的调用

在此处输入图像描述

于 2022-01-21T07:06:25.750 回答