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?
» element Function element retrieves a single element from a list. The index is zero-based.
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.
flatten Function flatten takes a list and replaces any elements that are lists with a flattened sequence of the list contents.
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,]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With