gpt4 book ai didi

terraform - terraform中的非空字符串是否正确?

转载 作者:行者123 更新时间:2023-12-03 15:24:33 27 4
gpt4 key购买 nike

documentation或他们的bug database中,两位作者似乎都更喜欢这样写表达式:

var.a != "" ? var.a : "default-a"

该值被显式测试为不等于空字符串,然后相应地进行二进制选择。

但是,这也可以吗?
var.a ? var.a : "default-a"

我还没有找到明确指出的任何一种方式。

最佳答案

在Terraform 0.12之前的版本中,Terraform在幕后使用强制类型对 bool 值和整数进行了一些有趣的处理,因为从技术上讲,它仅支持字符串,列表和映射。

因此,如果您执行以下操作:

variable "foo" {
default = "true"
}

output "truthiness" {
value = "${var.foo ? var.foo : "default-foo" }"
}

那么您可以期待以下输出:
$ terraform apply
Using temporary credentials from master-read-only profile...

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

truthiness = true
$ TF_VAR_foo=false terraform apply
Using temporary credentials from master-read-only profile...

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

truthiness = default-foo

这甚至适用于 01:
$ TF_VAR_foo=1 terraform apply
Using temporary credentials from master-read-only profile...

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

truthiness = 1
$ TF_VAR_foo=0 terraform apply
Using temporary credentials from master-read-only profile...

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

truthiness = default-foo


但是,如果您尝试使用Terraform无法将强制类型输入为 bool 值的字符串,则它将无法解析,并且会出错:
$ TF_VAR_foo="" terraform apply
Using temporary credentials from master-read-only profile...

Error: output.truthiness: __builtin_StringToBool: strconv.ParseBool: parsing "": invalid syntax in:

${var.foo ? var.foo : "default-foo" }
$ TF_VAR_foo="bar" terraform apply
Using temporary credentials from master-read-only profile...

Error: output.truthiness: __builtin_StringToBool: strconv.ParseBool: parsing "bar": invalid syntax in:

${var.foo ? var.foo : "default-foo" }
$ TF_VAR_foo=2 terraform apply
Using temporary credentials from master-read-only profile...

Error: output.truthiness: __builtin_StringToBool: strconv.ParseBool: parsing "2": invalid syntax in:

${var.foo ? var.foo : "default-foo" }

关于terraform - terraform中的非空字符串是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56967975/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com