'How to append to a list in Terraform?

I have some code in the general form:

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

resource "bar_type" "bar" {
  bar_field = "${var.foo}"
}

I want to append an addition value to bar_field without modifying foo. How can I do this? I don't see any sort of contacting or appending functions in their docs.

This is 0.11.x Terraform



Solution 1:[1]

You can use the concat function for this. Expanding upon the example in your question:

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

# assume a value of 4 of type number is the additional value to be appended
resource "bar_type" "bar" {
  bar_field = "${concat(var.foo, [4])}"
}

which appends to the value assigned to bar_field while ensuring var.foo remains unchanged.

Solution 2:[2]

var1 = ["string1","string2"]

var2 = "string3"

var3 = concat(var1, formatlist(var2))

Solution 3:[3]

Adding new item to the list if not present:

locals {

  oldlist = ["a", "b", "c"]
  newitem = "d"

  newlist = (contains(local.oldlist, local.newitem) == false ? concat(local.oldlist, [local.newitem]) : local.oldlist)

}

output "newlist" {
  value = local.newlist
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 jmoerdyk
Solution 3 OlegG