Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

terraform: performing a map operation on a list?

Tags:

terraform

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?

like image 930
Dotan Avatar asked Jul 10 '18 14:07

Dotan


People also ask

What Terraform function is used to return a single element from a list at the given index?

» element Function element retrieves a single element from a list. The index is zero-based.

What is Tomap in Terraform?

tomap Function tomap converts its argument to a map value. Explicit type conversions are rarely necessary in Terraform because it will convert types automatically where required. Use the explicit type conversion functions only to normalize types returned in module outputs.

What is flatten Terraform?

flatten Function flatten takes a list and replaces any elements that are lists with a flattened sequence of the list contents.


2 Answers

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,]

like image 163
Claire Furney Avatar answered Nov 15 '22 09:11

Claire Furney


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.

like image 39
Rowan Jacobs Avatar answered Nov 15 '22 09:11

Rowan Jacobs