Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform get the length of list

Tags:

terraform

I'm experimenting with Terraform and I came across locals. What I'm trying to do is to get the length of the list based on another varibale (env).

how can to make terrform to evaluate the variable before getting trying to evaluate the length?

This is my code:

locals {
  env = "${terraform.workspace}"

  subnet_names = {
    "default" = ["default_sub1"]
    "dev"     = ["dev_sub1", "dev_sub2", "dev_sub3"]
    "prod"    = ["prod_sub1", "prod_sub2", "prod_sub3"]
  }

}

resource "azurerm_subnet" "subnet" {
  name                      = "${lookup(local.subnet_names, local.env, count.index)}"
  virtual_network_name      = "${azurerm_virtual_network.network.name}"
  resource_group_name       = "${azurerm_resource_group.terraform.name}"
  address_prefix            = "10.0.1.0/24"
  network_security_group_id = "${azurerm_network_security_group.security_group.id}"
  count                     =  "${length(local.subnet_names, local.env)}"
}

When I try to validate the code I get this length: expected 1 arguments, got 2 in: ${length(local.subnet_names, local.env)}

What is the trick here?

like image 836
MMT Avatar asked Nov 02 '17 16:11

MMT


People also ask

What is Terraform length function?

length Function length determines the length of a given list, map, or string. If given a list or map, the result is the number of elements in that collection. If given a string, the result is the number of characters in the string.

What is Count Index Terraform?

What is count in Terraform? When you define a resource block in Terraform, by default, this specifies one resource that will be created. To manage several of the same resources, you can use either count or for_each , which removes the need to write a separate block of code for each one.

What is Terraform Toset?

toset converts its argument to a set 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.


1 Answers

Your local.subnet_names is not a list, it is a map and can be accessed as explained in the interpolation syntax:

${length(local.subnet_names[local.env])}

EDIT:

As for the name variable, the right way to make it is using the element interpolation:

name = "${element(local.subnet_names[local.env], count.index)}"

This is due to the fact that local.subnet_names[local.env] will return a list. As an example, if local.env is "dev", it will return

["dev_sub1", "dev_sub2", "dev_sub3"]

and to get an element in a certain index in a list we use element.

like image 109
aderubaru Avatar answered Sep 28 '22 07:09

aderubaru