如何通过 terraform 使用服务帐户创建 google 云 pubsub 订阅?

How to create a google cloud pubsub subscriptions with service account by terraform?

根据这个文档,我想通过 terraform 创建同样的东西。

https://cloud.google.com/run/docs/tutorials/pubsub

gcloud pubsub subscriptions create myRunSubscription --topic myRunTopic \
   --push-endpoint=SERVICE-URL/ \
   --push-auth-service-account=cloud-run-pubsub-invoker@PROJECT_ID.iam.gserviceaccount.com

terraform 的 main.tf

resource "google_pubsub_subscription" "my_task" {
  name  = "my-task-subscription"
  topic = google_pubsub_topic.my_task.name

  ack_deadline_seconds = 20

  push_config {
    push_endpoint = var.push_endpoint
  }

  dead_letter_policy {
    dead_letter_topic = "cloud-run-pubsub-invoker@my-project.iam.gserviceaccount.com"
  }
}

地形应用

  # module.pubsub.google_pubsub_subscription.my_task will be created
  + resource "google_pubsub_subscription" "my_task" {
      + ack_deadline_seconds       = 20
      + id                         = (known after apply)
      + message_retention_duration = "604800s"
      + name                       = "my-task-subscription"
      + path                       = (known after apply)
      + project                    = (known after apply)
      + topic                      = "MyTask"

      + dead_letter_policy {
          + dead_letter_topic = "cloud-run-pubsub-invoker@my-project.iam.gserviceaccount.com"
        }

      + expiration_policy {
          + ttl = (known after apply)
        }

      + push_config {
          + push_endpoint = "https://an-endpoint.com"
        }
    }

出现错误:

Error: Error creating Subscription: googleapi: Error 400: Invalid resource name given (name=cloud-run-pubsub-invoker@my-project.iam.gserviceaccount.com). Refer to https://cloud.google.com/pubsub/docs/admin#resource_names for more information.

根据 terraform 的文档,dead_letter_policy 与 Pub/Sub 服务帐户相关: https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/pubsub_subscription#dead_letter_policy

但为什么不起作用?那怎么把--push-auth-service-account设置成google官方呢?

您链接的 Terraform 文档如下所述。

The Cloud Pub/Sub service account associated with this subscription's parent project (i.e., service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) must have permission to Acknowledge() messages on this subscription.

您用于死信策略的服务帐户似乎没有适当的权限来确认消息。

根据 IAM 文档,它至少需要 pub/sub 订阅者 角色才能确认消息。

参考 here 获取有关 pubsub 角色的更多信息。

你的问题在这里:

  dead_letter_policy {
    dead_letter_topic = "cloud-run-pubsub-invoker@my-project.iam.gserviceaccount.com"
  }

您正在尝试将服务帐户身份分配给 dead_letter_topic。这是不正确的。

而是使用类似这样的东西来创建主题:

resource "google_pubsub_topic" "example_dead_letter" {
  name = "example-topic-dead-letter"
}

或引用现有主题:

data "google_pubsub_topic" "example_dead_letter" {
  name = "example-topic-dead-letter"
}

然后像这样使用该资源:

  dead_letter_policy {
    dead_letter_topic = google_pubsub_topic.example_dead_letter.id
  }