Jayendran
Jayendran

Reputation: 10960

Terraform : How to ignore the Optional block if the Property - list of string is Empty

I'm just starting with the terraform, The below is my terraform code. From the below Cors is an Optional block, where it has the property of allowed origins which is list of strings(URL or *)

resource "azurerm_signalr_service" "signalr_service" {
  
  name="${var.signalr_name}"
  location = "${var.resource_location}"
  resource_group_name = "${var.resource_group_name}"

  sku {
    name     = "${var.sku_name}"
    capacity = "${var.sku_capacity}"
  }
        
#Cors is an optional block
  cors {
    allowed_origins = "${var.cors_allowed_origins}"
  }

Varilabe.tf:

variable "allowed_origins" {
  type = "list"
  description = "A list of origins which should be able to make cross-origin calls. * can be used to allow all calls"
  default = []
}

Users may/maynot provide the allowed_origns , if they provide there is no problem, but if they don't provide

  1. Default as an empty list[]: when I pass the empty list the allowed_origns it fails saying that not a valid URL
  2. Default as an null: If I pass as null, allowed_origin alone gets null and cors is passing as an empty block i.e,cors{} which also fails due to property missing error

Now my question is how to make the entire cors block to ignore if the user doesn't provide any values to the allowed_origins and what would be the default I should use ?

Upvotes: 6

Views: 4477

Answers (1)

Marcin
Marcin

Reputation: 238957

You can use dynamic blocks to make CORS block optional:

resource "azurerm_signalr_service" "signalr_service" {
  
  name="${var.signalr_name}"
  location = "${var.resource_location}"
  resource_group_name = "${var.resource_group_name}"

  sku {
    name     = "${var.sku_name}"
    capacity = "${var.sku_capacity}"
  }
        
  dynamic "cors" {
    for_each = length(var.cors_allowed_origins) > 0 ? [1] : []
    content {
        allowed_origins = "${var.cors_allowed_origins}"
    }
  }
}

Default value of [] is fine.

Upvotes: 9

Related Questions