14

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?

2 Answers 2

13

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) : ""}
Sign up to request clarification or add additional context in comments.

2 Comments

I found out about this in the meantime too, thanks. I think you can remove the boolean condition though? element will wrap around the index if it surpasses the list's length, so just looking up list("") should work in case there are no volumes .
The truth, of course, is that Terraform is not a language, it is a config file format. What we need are tools that wrap Terraform, like stack_master/stacker/etc. for CloudFormation, which let you code in proper programming languages.
3

Since this answer was written, several new constructs make this problem just a little less gross. As of terraform 1.x syntax can be changed from:

element(concat(digitalocean_volume.worker.*.id , list(""))
coalescelist(digitalocean_volume.worker[*].id, [""])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.