Maya Ray
Maya Ray

Reputation: 549

Terraform condition not working for empty value

I am running a condition in terraform. If the publicA is empty, it shouldn't create any subnet. Below is the code and error. Please help. env.tfvars:

subnets_cidrs = [
  {
    vpc_cidr = "10.150.0.0/20"
    publicA            = [""]               #list of IPs
    privateA           = ["10.150.0.0/23","10.150.9.0/26","10.150.7.0/24"] #list of IPs
    publicB            = [""]              #list of IPs
    privateB           = ["10.150.2.0/23","10.150.9.64/26","10.150.8.0/24"] #list of IPs
    publicC            = [""]           #list of IPs
    privateC           = ["10.150.4.0/23","10.150.9.128/26","10.150.6.0/24"]                                #list of IPs
  },

variables.tf

variable "subnets_cidrs" {
  type = list(object({
    vpc_cidr = string
    publicA            = list(string)              #list of IPs
    privateA           = list(string)              #list of IPs
    publicB            = list(string)               #list of IPs
    privateB           = list(string)               #list of IPs
    publicC            = list(string)             #list of IPs
    privateC           = list(string)  
  }))
}

main.tf

resource "aws_subnet" "VPC1PublicSubnetA" {
  count = var.subnets_cidrs[0].vpc_cidr != "" ? length(var.subnets_cidrs[0].publicA) : 0
  vpc_id                  = aws_vpc.VPC1.id
  cidr_block              = var.subnets_cidrs[0].publicA[count.index]
  availability_zone       = element(var.AvailabilityZonesForVPC,0)
  
}

Error:

in resource "aws_subnet" "VPC1PublicSubnetA":
  60:   cidr_block              = var.subnets_cidrs[0].publicA[count.index]



Error: "" is not a valid CIDR block: invalid CIDR address

Upvotes: 0

Views: 948

Answers (2)

S.K.
S.K.

Reputation: 77

You need to pass empty list [] instead of [""]

Upvotes: 0

Marcin
Marcin

Reputation: 238957

The length of [""] is 1. So your code will always try to run once. To make it zero, use []:

  {
    vpc_cidr = "10.150.0.0/20"
    publicA            = []               #list of IPs
    privateA           = ["10.150.0.0/23","10.150.9.0/26","10.150.7.0/24"] #list of IPs
    publicB            = []              #list of IPs
    privateB           = ["10.150.2.0/23","10.150.9.64/26","10.150.8.0/24"] #list of IPs
    publicC            = []           #list of IPs
    privateC           = ["10.150.4.0/23","10.150.9.128/26","10.150.6.0/24"]                                #list of IPs
  }

Upvotes: 2

Related Questions