条件表达式中的 zipmap 函数给出真假结果表达式必须具有一致的类型错误

Posted

技术标签:

【中文标题】条件表达式中的 zipmap 函数给出真假结果表达式必须具有一致的类型错误【英文标题】:zipmap function in condition expression giving true and false result expressions must have consistent types error 【发布时间】:2021-10-03 07:42:38 【问题描述】:

变量: ingress_ports_udp 是带有逗号分隔值的字符串类型。 ingress_cidr_udp 是带有逗号分隔值的字符串类型。

代码:

  dynamic "ingress" 
    iterator           = rule
    for_each           = zipmap(split(",", var.ingress_ports_udp),split(",", var.ingress_cidr_udp)) != "" ? zipmap(split(",", var.ingress_ports_udp),split(",", var.ingress_cidr_udp)) : ""
    content 
      from_port        = rule.key
      to_port          = rule.key
      protocol         = "udp"
      cidr_blocks      = rule.value
    
  

问题: 表达式 zipmap(split(",", var.ingress_ports_udp),split(",", var.ingress_cidr_udp)) != "" 出现错误? zipmap(split(",", var.ingress_ports_udp),split(",", var.ingress_cidr_udp)) : ""

"msg": "Failed to validate Terraform configuration files:\r\n\u001b[31m\n\u001b[1m\u001b[31mError: \u001b[0m\u001b[0m\u001b[1mInconsistent conditional result types\u001b[0m\n\n\u001b[0m  on security-group.tf line 9, in resource \"aws_security_group\" \"default-sg\":\n   9:     for_each           = zipmap(split(\",\", var.ingress_ports_udp),split(\",\", var.ingress_cidr_udp)) != \"\" ? \u001b[4mzipmap(split(\",\", var.ingress_ports_udp),split(\",\", var.ingress_cidr_udp)) : \"\"\u001b[0m\n\u001b[0m\nThe true and false result expressions must have consistent types. The given\nexpressions are map of string and string, respectively.\n\u001b[0m\u001b[0m\n\u001b[31m\n\u001b[1m\u001b[31mError: \u001b[0m\u001b[0m\u001b[1mInconsistent conditional result types\u001b[0m\n\n\u001b[0m  on security-group.tf line 20, in resource \"aws_security_group\" \"default-sg\":\n  20:     for_each           = zipmap(split(\",\", var.ingress_ports_udp),split(\",\", var.ingress_cidr_udp)) != \"\" ? \u001b[4mzipmap(split(\",\", var.ingress_ports_udp),split(\",\", var.ingress_cidr_udp)) : \"\"\u001b[0m\n\u001b[0m\nThe true and false result expressions must have consistent types. The given\nexpressions are map of string and string, respectively.\n\u001b[0m\u001b[0m\n"

要求: 如果 zipmap(split(",", var.ingress_ports_udp),split(",", var.ingress_cidr_udp)) 为空,即 ingress_ports_udp 和 ingress_cidr_udp 字符串类型为空,我不想运行动态入口块。 请帮忙。

【问题讨论】:

【参考方案1】:

false 不能使用空字符串,因为它的类型与true 条件的结果不同。您可以检查:

for_each           = zipmap(split(",", var.ingress_ports_udp),split(",", var.ingress_cidr_udp)) != "" ? zipmap(split(",", var.ingress_ports_udp),split(",", var.ingress_cidr_udp)) : 

【讨论】:

以上是关于条件表达式中的 zipmap 函数给出真假结果表达式必须具有一致的类型错误的主要内容,如果未能解决你的问题,请参考以下文章

条件语句

JS

HTML-JS 循环 函数 递归

Golang入门到项目实战 golang中的if语句

python中循环语句

JS学习