amazon-web-servicesterraformterraform-provider-awsamazon-vpchcl

Using element function within resource block


I am using aws vpc module and defined below variables. I am trying to understand use of element and why the cidr_block is calculated as below:

element(concat(var.public_cidr_blocks, [""]), count.index)

Below are the variable and resource block.

variable "public_cidr_blocks" {
  type = list(string)
  default = [
    "182.10.10.0/24",
    "182.10.20.0/24"
  ]
}


variable "availability_zones" {
  type = list(string)
  default = [
    "us-east-2a",
    "us-east-2b"
  ]
}

resource "aws_subnet" "aws_public_subnets" {
  vpc_id                  = aws_vpc.myvpc.id
  cidr_block              = element(concat(var.public_cidr_blocks, [""]), count.index)
  availability_zone       = element(var.availability_zones, count.index)
  map_public_ip_on_launch = true
  count                   = length(var.public_cidr_blocks)
}

My question is why [""] has to be concated here in the elements function.


Solution

  • element(concat(var.public_cidr_blocks, [""]), count.index)
    

    What this line does, it makes sure that there is at least one element in the list, no matter what is the input for public_cidr_blocks.

    The reason for this, I think, is an older issue from Terraform. I assume your module is based on the terraform-aws-modules implementation. In an older version of Terraform and/or terraform-provider-aws, there was with this error with detecting the type for elements in a list:

    "var.public_subnets" does not have any elements so cannot determine type
    

    To have a workaround for this, the fix was to add at list one element to the list which had the type of string. See this pull request: https://github.com/terraform-aws-modules/terraform-aws-vpc/issues/177

    With newer versions of Terraform this issue was fixed. That line does not make much sense anymore.