使用 terraform 脚本的 pubsub 主题和订阅之间的依赖关系

Dependency between pubsub topic and subscription using terraform script

我正在使用一个 Terraform 脚本来创建发布子主题和订阅。如果订阅需要从同一脚本创建的主题订阅,有没有办法创建依赖关系,以便 terraform 仅在创建主题后才尝试创建 pub/sub 订阅? 我的主文件如下所示:

  version = ""

  project = var.project_id
  region  = var.region
  zone    = var.zone
}
    
# module "Dataflow" {
 #source = "../modules/cloud-dataflow"
#} 

module "PubSubTopic" {
 source = "../modules/pubsub_topic"
}

#module "PubSubSubscription" {
# source = "../modules/pubsub_subscription"
#}

#module "CloudFunction" {
# source = "../modules/cloud-function"
#}


您可以使用此代码段在您的文件系统上创建一个简单的 pubsub 主题和订阅(只需为具有足够权限的服务帐户添加 .json):

provider "google" {
  credentials = "${file("account.json")}" # Or use GOOGLE_APPLICATION_CREDENTIALS
  project     = "__your_project_id__"
  region      = "europe-west4" # Amsterdam
}

resource "google_pubsub_topic" "incoming_data" {
  name = "incoming-data"
}

resource "google_pubsub_subscription" "incoming_subs" {
  name = "Subscription_for_incoming_data"
  topic =  google_pubsub_topic.incoming_data.name

  # Time since Pubsub receives a message  to deletion.
  expiration_policy {
    ttl = "300000s"
  }

  # Time from client reception to ACK
  message_retention_duration = "1200s"
  retain_acked_messages      = false
  enable_message_ordering    = false
}

要link 订阅一个带有 terraform 主题的订阅,您只需要 link 使用:

topic = google_pubsub_topic.TERRAFORM_TOPIC.name

注意主题和订阅标识符的 Google 要求。如果它们无效,terraform plan 将通过,但你会得到一个 Error 400 : You have passed an invalid argument to the service

Terraform 将尝试按照正确的顺序创建资源,但要回答您的问题以及您要查找的是模块依赖项“depends_on”。

例如,订阅模块只有在创建主题资源后才会创建。这样你应该在订阅模块上添加 depends_on。

示例:

resource "aws_iam_policy_attachment" "example" {
  name       = "example"
  roles      = [aws_iam_role.example.name]
  policy_arn = aws_iam_policy.example.arn
}

module "uses-role" {
  # ...

  depends_on = [aws_iam_policy_attachment.example]
}

官方文档:https://www.terraform.io/docs/language/meta-arguments/depends_on.html