Terraform 条件不适用于空值

Terraform condition not working for empty value

我是 运行 terraform 中的一个条件。如果 publicA 为空,则不应创建任何子网。下面是代码和错误。请帮忙。 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)
  
}

错误:

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

[""] 的长度为 1。因此您的代码将始终尝试 运行 一次。要使其为零,请使用 []:

  {
    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
  }

您需要传递空列表 [] 而不是 [""]