我的 terraform 代码中有一个属性“my_code”。目前,用户提供这样的输入
my_code = "15"
但我们希望将其从数字更改为列表,以便用户可以像上面一样提供他们现在正在执行的数字(以便保持向后兼容),或者他们可以提供如下所示的数字列表
my_code = ["15", "20"]
目前我的 terraform 代码如下所示
my_code = lookup(all_operations, "my_code", null)
我正在考虑做类似下面的事情,以便它同时采用这两个值。如果它是一个数字,它会将其转换为一个列表,如果它已经是一个列表,它会保持原样。
my_code = can(list, lookup(all_operations, "my_code", null)) ? [lookup(all_operations, "my_code", null)] : lookup(all_operations, "my_code", null)
但是由于这个错误,我遇到了以下错误
my_code = can(list, lookup(all_operations, "my_code", null)) ? [lookup(all_operations, "my_code", null)] : lookup(all_operations, "my_code", null)
│
│ A reference to a resource type must be followed by at least one attribute
│ access, specifying the resource name
尝试如下
my_code = type(lookup(all_operations, "my_code", null)) == list(any) ? lookup(all_operations, "my_code", null) : [lookup(all_operations, "my_code", null)]
遇到同样的错误
my_code = type(lookup(all_operations, "my_code", null)) == list(any) ? lookup(all_operations, "my_code", null) : [lookup(all_operations, "my_code", null)]
│
│ A reference to a resource type must be followed by at least one attribute
│ access, specifying the resource name
任何帮助将不胜感激。预先感谢
您可以使用 flatten 为这两种情况生成元素数组:
my_code
包含单个值,例如 "15"
my_code
包含一个数组,例如 ["15", "20"]
示例:
variable "my_code" {
}
locals {
# square brackets [] are required in order to convert var.my_code to an array
#
# If var.my_code is already an array that's ok, as flatten(...) will return
# a flattened sequence of elements for single or multi-dimensional arrays
my_codes = flatten([var.my_code])
}
output "my_codes" {
value = local.my_codes
}
使用单个字符串值 (
terraform plan
) 运行 mycode = "15"
:
Changes to Outputs:
+ my_codes = [
+ "15",
]
使用字符串数组 (
terraform plan
) 运行 mycode = ["15", "20"]
:
Changes to Outputs:
+ my_codes = [
+ "15",
+ "20",
]