You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform字母数字字符串列表变量验证失败问题排查

Terraform列表变量字母数字验证失败问题解决

问题分析

你的变量验证逻辑存在错误:外层多余的can()函数导致验证逻辑不符合预期。

all()函数接收布尔值列表后,会直接返回一个布尔值(所有元素为true则返回true,否则返回false),这个执行过程不会抛出错误。因此can(all(...))永远返回true(因为all()执行不会出错),但这并非你需要的验证逻辑——你需要的是all()的返回值来判断所有元素是否符合规则,而不是判断all()是否能执行成功。

修复后的代码

将验证条件中的外层can()移除,直接使用all()的返回值作为判断条件:

variable "list_of_strings" {
  type        = list(string)
  description = "List of alphanumeric strings (case-insensitive)"

  validation {
    condition = all([
      for value in var.list_of_strings : can(regex("^[A-Za-z0-9]*$", value))
    ])
    error_message = "list_of_strings must contain only alphanumeric strings (case-insensitive)."
  }
}

额外优化

如果不希望允许空字符串(原正则中的*允许零次匹配,空字符串也会通过验证),可以将正则中的*改为+,要求至少有一个字母数字字符:

condition = all([
  for value in var.list_of_strings : can(regex("^[A-Za-z0-9]+$", value))
])

内容的提问来源于stack exchange,提问作者Geert Smelt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 05:14:59