one
函数
one
接收一个列表、集合或元组值,其中包含零个或一个元素。如果集合为空,one
返回 null
。否则,one
返回第一个元素。如果存在两个或多个元素,则 one
将返回错误。
这是一个专门的函数,用于常见的场景,其中条件项表示为零个或一个元素的列表,模块作者希望返回一个可能为 null 的单个值。
例如
variable "include_ec2_instance" {
type = bool
default = true
}
resource "aws_instance" "example" {
count = var.include_ec2_instance ? 1 : 0
# (other resource arguments...)
}
output "instance_ip_address" {
value = one(aws_instance.example[*].private_ip)
}
由于上面的 aws_instance
资源的 count
参数设置为返回零或一的条件,因此 aws_instance.example
的值为零个或一个元素的列表。instance_ip_address
输出值使用 one
函数作为一种简洁的方法来返回单个实例的私有 IP 地址,或者如果未创建任何实例,则返回 null
。
与“展开”运算符的关系
OpenTofu 语言有一个内置运算符 [*]
,称为 展开运算符,它的一个功能是将可能为 null 的原始值转换为零个或一个元素的列表。
variable "ec2_instance_type" {
description = "The type of instance to create. If set to null, no instance will be created."
type = string
default = null
}
resource "aws_instance" "example" {
count = length(var.ec2_instance_type[*])
instance_type = var.ec2_instance_type
# (other resource arguments...)
}
output "instance_ip_address" {
value = one(aws_instance.example[*].private_ip)
}
在这种情况下,我们可以看到,从某种意义上说,one
函数与对原始类型值应用 [*]
相反。展开可以将可能为 null 的值转换为零个或一个元素的列表,而 one
可以反转该操作,以返回一个可能为 null 的原始值。
示例
> one([])
null
> one(["hello"])
"hello"
> one(["hello", "goodbye"])
Error: Invalid function argument
Invalid value for "list" parameter: must be a list, set, or tuple value with
either zero or one elements.
使用 one
与集合
one
函数在您有一个已知仅包含零个或一个元素的集合的情况下特别有用。集合值不支持索引,因此编写 var.set[0]
来提取集合的“第一个”元素是无效的,但如果您知道只有一个项目,则 one
可以隔离并返回该单个项目。
> one(toset([]))
null
> one(toset(["hello"]))
"hello"
不要将 one
用于可能包含多个元素的集合。在这种情况下,该函数将失败。
> one(toset(["hello","goodbye"]))
Error: Invalid function argument
Invalid value for "list" parameter: must be a list, set, or tuple value with
either zero or one elements.