- OpenTofu 语言
- 函数
- yamldecode
yamldecode
函数
yamldecode
将字符串解析为 YAML 的一个子集,并生成其值的表示。
此函数支持 YAML 1.2 的一个子集,如下所述。
此函数以以下方式将 YAML 值映射到 OpenTofu 语言值
YAML 类型 | OpenTofu 类型 |
---|---|
!!str | string |
!!float | number |
!!int | number |
!!bool | bool |
!!map | object(...) ,属性类型根据此表确定 |
!!seq | tuple(...) ,元素类型根据此表确定 |
!!null | OpenTofu 语言的 null 值 |
!!timestamp | string ,采用 RFC 3339 格式 |
!!binary | string ,包含 base64 编码的表示 |
OpenTofu 语言的自动类型转换规则意味着您通常不必担心为给定值生成的精确类型,并且可以以直观的方式使用结果。
但是请注意,上面的映射是模棱两可的 - 几个不同的源类型映射到相同的目标类型 - 因此通过 yamldecode
和 yamlencode
进行循环往复无法生成相同的结果。
YAML 是一种复杂的语言,它支持 OpenTofu 语言的类型系统无法表示的多种可能性。因此,此 YAML 解码器只支持 YAML 1.2 的一个子集,限制包括以下内容
-
虽然支持对先前锚点的别名,但不支持循环数据结构(其中对集合的引用出现在该集合内)。如果
yamldecode
检测到这种结构,则它将返回错误。 -
只支持上面表格中显示的类型标签(或这些相同标签的等效替代表示)。任何其他标签都会导致错误。
-
只允许一个 YAML 文档。如果给定字符串中存在多个文档,则此函数将返回错误。
示例
> yamldecode("hello: world")
{
"hello" = "world"
}
> yamldecode("true")
true
> yamldecode("{a: &foo [1, 2, 3], b: *foo}")
{
"a" = [
1,
2,
3,
]
"b" = [
1,
2,
3,
]
}
> yamldecode("{a: &foo [1, *foo, 3]}")
Error: Error in function call
Call to function "yamldecode" failed: cannot refer to anchor "foo" from inside
its own definition.
> yamldecode("{a: !not-supported foo}")
Error: Error in function call
Call to function "yamldecode" failed: unsupported tag "!not-supported".
相关函数
jsondecode
是使用 JSON 而不是 YAML 的类似操作。yamlencode
执行相反的操作,即以 YAML 编码 值。