跳至主要内容

type 函数

type 返回给定值的类型。

有时 OpenTofu 配置会导致关于类型不一致的令人困惑的错误。此函数显示 OpenTofu 对给定值类型的评估,这有助于理解此错误消息。

这是一个特殊函数,仅在 tofu console 命令中可用。它只能用于检查给定值的类型,不应在更复杂的表达式中使用。

示例

这里我们有一个条件 output,它打印 var.list 的值或名为 default_list 的本地值。

代码块
variable "list" {
default = []
}

locals {
default_list = [
{
foo = "bar"
map = { bleep = "bloop" }
},
{
beep = "boop"
},
]
}

output "list" {
value = var.list != [] ? var.list : local.default_list
}

应用此配置会导致以下错误

代码块
Error: Inconsistent conditional result types

on main.tf line 18, in output "list":
18: value = var.list != [] ? var.list : local.default_list
|----------------
| local.default_list is tuple with 2 elements
| var.list is empty tuple

The true and false result expressions must have consistent types. The given
expressions are tuple and tuple, respectively.

虽然此错误消息确实包含一些类型信息,但检查 OpenTofu 确定的每个给定输入的精确类型可能会有所帮助。使用 type 函数检查 var.listlocal.default_list 为错误消息提供了更多上下文

代码块
> type(var.list)
tuple
> type(local.default_list)
tuple([
object({
foo: string,
map: object({
bleep: string,
}),
}),
object({
beep: string,
}),
])