Terraform-为变量指定多个可能的值 [英] Terraform - Specifying multiple possible values for Variables
问题描述
CloudFormation提供了用于参数的AllowedValues,它指示该参数的可能值可以来自此列表。如何使用Terraform变量实现这一目标?列表的变量类型不提供此功能。因此,如果我希望变量仅具有两个可能的值,那么如何使用Terraform来实现这一点。我要复制的CloudFormation脚本是:
CloudFormation provides AllowedValues for Parameters which tells that the possible value of the parameter can be from this list. How can I achieve this with Terraform variables? The variable type of list does not provide this functionality. So, in case I want my variable to have value out of only two possible values, how can I achieve this with Terraform. CloudFormation script that I want to replicate is:
"ParameterName": {
"Description": "desc",
"Type": "String",
"Default": true,
"AllowedValues": [
"true",
"false"
]
}
推荐答案
我不知道官方的方式,但是在Terraform问题中描述了一种有趣的技术:
I don't know of an official way, but there's an interesting technique described in a Terraform issue:
variable "values_list" {
description = "acceptable values"
type = "list"
default = ["true", "false"]
}
variable "somevar" {
description = "must be true or false"
}
resource "null_resource" "is_variable_value_valid" {
count = "${contains(var.values_list, var.somevar) == true ? 0 : 1}"
"ERROR: The somevar value can only be: true or false" = true
}
更新:
现在,Terraform提供了实验性设置,可以启用自定义验证规则,尽管他们不建议在生产模块中使用它:
Terraform now offers an experimental setting to enable custom validation rules, though they don't recommend using this in production modules yet:
variable "somevar" {
type = string
description = "must be true or false"
validation {
condition = can(regex("^(true|false)$", var.somevar))
error_message = "Must be true or false."
}
}
这篇关于Terraform-为变量指定多个可能的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!