I am going through the aws_subnet
resource implementation within terraform-aws-modules
I need help to understand the below two expressions:
resource "aws_subnet" "public" {
count = local.create_public_subnets && (!var.one_nat_gateway_per_az || local.len_public_subnets >= length(var.azs)) ? local.len_public_subnets : 0
availability_zone = length(regexall("^[a-z]{2}-", element(var.azs, count.index))) > 0 ? element(var.azs, count.index) : null
...
}
The condition (!var.one_nat_gateway_per_az || local.len_public_subnets >= length(var.azs))
is checking whether the number of public subnets to be created should be based on the number of AZs or should be limited by the number of public subnets specified by local.len_public_subnets
.
If var.one_nat_gateway_per_az
is false or the number of desired public subnets is greater than or equal to the number of AZs, then it creates local.len_public_subnets
subnets. Otherwise, it creates 0 subnets.
The availability_zone parameter is used to specify the availability zone for each subnet. It uses the element function to retrieve the availability zone from the list of AZs (var.azs) based on the count.index, which iterates over the number of subnets to create.
length(regexall("^[a-z]{2}-",element(var.azs, count.index)))
is checking whether the availability zone retrieved from the var.azs list matches the pattern, two lowercase letters followed by a hyphen. This is done to ensure that the availability zone is in the format of us-east-1a
If the availability zone matches the correct format, it will be used for the subnet's availability_zone. Otherwise, it will be set to null.
In conclusion: a public AWS subnet/s will be created based on some conditions.