Search code examples
amazon-web-servicesterraformamazon-elastic-beanstalkterraform-provider-aws

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


I have an Elastic Beanstalk resource that contains several optional settings. One of these is a queue depending on whether the tier of the EB is worker or not.

The template that calls this module has a value worker.

What I'd like to do is something that achieves the following: if tier == worker; assert queue != null

I've looked at the count meta believing this may be the correct path but I cannot piece it together.

My current iteration is this but I feel it's too convoluted and there is a better approach(and it doesn't work):

/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"
///
}

as an extension of this, I'd like to enforce that the queue name and url is set. For example, I have:

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"
}

Currently, these can be empty strings when creating a worker which I'd really like to update so that `if worker; var.queue != ""


Solution

  • You can do that with 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.
        }
      }
    }