Terraform 条件 - 断言资源的定义取决于变量是 x 还是 y

Terraform conditional - assert resource is defined depending on if a variable is x or y

我有一个包含多个可选设置的 Elastic Beanstalk 资源。其中之一是队列,取决于 EB 的 tier 是否为 worker

调用该模块的模板有值worker

我想做的是实现以下目标: if tier == worker; assert queue != null

我查看了 count 元数据,认为这可能是正确的路径,但我无法将其拼凑起来。

我目前的迭代是这样的,但我觉得它太复杂了,有更好的方法(但它不起作用):

/eb template
resource "aws_elastic_beanstalk_environment" "default" {
  name                   = var.name
  application            = var.application_name
  tier                   = var.tier
  solution_stack_name    = var.solution_stack_name

  //Worker setting
  setting {
    //count     = var.is_worker_tier ? 1 : 0
    namespace = "aws:elasticbeanstalk:sqsd"
    name      = var.worker_queue_name
    value     = var.queue //only set if worker.
  }
}

//vars
variable "is_worker_tier" {
  type = boolean
  default = false
  description = "when true will create the sqs queue optional setting"
}

//where the module is called
module "test_beanstalk_3" {
  tier = "Worker"
  queue = "myQueue"
///
}

作为对此的扩展,我想强制设置队列名称和 url。 例如,我有:

variable "worker_queue_name" {
  type = string
  default = "WorkerQueueURL"
  description = "name of the worker queue, replace with arn if able to."
}

variable "queue" {
  type = string
  default = ""
  description = "List of application subnet ids"
}

目前,在创建一个我真的很想更新的 worker 时,这些可以是空字符串,以便 `if worker; var.queue != ""

你可以用 dynamic block:

resource "aws_elastic_beanstalk_environment" "default" {
  name                   = var.name
  application            = var.application_name
  tier                   = var.tier
  solution_stack_name    = var.solution_stack_name

  //Worker setting
  dynamic "setting"{
    for_each = var.tier == "Worker" ? [1] : [] 
    content {
      namespace = "aws:elasticbeanstalk:sqsd"
      name      = var.worker_queue_name
      value     = var.queue //only set if worker.
    }
  }
}