Dotan
Dotan

Reputation: 7622

terraform: performing a map operation on a list?

I have a terraform list

a = [1,2,3,4]

Is there a way for me to apply a function (e.g. *2) on the list, to get

b = [2,4,6,8]

I was looking for an interpolation syntax, perhaps map(a, _*2), or even something like

variable "b" {
   count = "${length(a)}"
   value = "${element(a, count.index)} * 2
}

As far as I can see no such thing exists. Am I missing something?

Upvotes: 13

Views: 9126

Answers (2)

Claire Furney
Claire Furney

Reputation: 2378

As per @Rowan Jacob's answer, this is now possible in v0.12 using the new for expression.

See: https://www.terraform.io/docs/configuration/expressions.html#for-expressions

variable "a" {
  type = "list"
  default = [1,2,3,4]
}

locals {
  b = [for x in var.a : x * 2]
}

output "local_b" {
  value = "${local.b}"
}

gives

Outputs:

local_b = [2, 4, 6, 8,]

Upvotes: 20

Rowan Jacobs
Rowan Jacobs

Reputation: 389

This is currently an open issue. A new version of Terraform was recently announced which should give the ability to do this, among many other HCL improvements.

I think currently your best bet would be to create local values for each element of the list (remember that you can't use interpolation syntax in the default value of variables; locals exist to get around this limitation). However, I'm not sure if locals have a count attribute.

Upvotes: 4

Related Questions