Search code examples
amazon-web-servicesterraformterraform-provider-awsamazon-vpcterraform0.12+

How to modify "availability_zone" when subnets is greater than availability zones?


I have aws_subnet resource which looks as below:

resource "aws_subnet" "public_subnets" {
  cidr_block              = element(concat(var.psubnets, [""]), count.index)
  availability_zone       = element(var.azs, count.index)
  count                   = length(var.psubnets)
}

Here, how to update availability_zone = element(var.azs, count.index) to account for the situation when

len.subnets > len.azs

Solution

  • The modulus operator should help you account for this:

    element(var.azs, count.index % len(var.azs))
    

    For example if the len(var.azs) value is 3, and you had 7 subnets, you would get the following:

    count.index len(var.azs) count.index % len(var.azs)
    0 3 0
    1 3 1
    2 3 2
    3 3 0
    4 3 1
    5 3 2
    6 3 0