Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a list in Terraform that may be empty depending on a variable?

Tags:

terraform

I need to define a resource in Terraform (v0.10.8) that has a list property that may or may not be empty depending on a variable, see volume_ids in the following definition:

resource "digitalocean_droplet" "worker_node" {
  count = "${var.droplet_count}"
  [...]
  volume_ids = [
    "${var.volume_size != 0 ? element(digitalocean_volume.worker.*.id, count.index) : ""}"
  ]
}

resource "digitalocean_volume" "worker" {
  count = "${var.volume_size != 0 ? var.droplet_count : 0}"
  [...]
}

}

The solution I've come up with fails however in the case where the list should be empty (i.e., var.volume_size is 0):

volume_ids = [
  "${var.volume_size != 0 ? element(digitalocean_volume.worker.*.id, count.index) : ""}"
]

The following Terraform error message is produced:

* module.workers.digitalocean_droplet.worker_node[1]: element: element() may not be used with an empty list in:

${var.volume_size != 0 ? element(digitalocean_volume.worker.*.id, count.index) : ""}

How should I correctly write my definition of volume_ids?

like image 385
aknuds1 Avatar asked Nov 21 '17 12:11

aknuds1


People also ask

How do I give a null value in Terraform?

The null value is represented by the unquoted symbol null .

How do you define optional variables in Terraform?

As this is an experimental, you firstly need to declare an “experiments” tag in the terraform block: terraform { experiments = [module_variable_optional_attrs] } Then, in your variable definition, use the “optional()” in the attribute definition.


1 Answers

Unfortunately this is one of many language shortcomings in terraform. The hacky workaround is to tack an empty list onto your empty list.

${var.volume_size != 0 ? element(concat(digitalocean_volume.worker.*.id , list("")), count.index) : ""}
like image 60
RaGe Avatar answered Sep 28 '22 01:09

RaGe