CloudFormation 为参数提供了 AllowedValues,它告诉参数的可能值可以来自此列表。如何使用地形变量实现此目的?列表的变量类型不提供此功能。因此,如果我希望我的变量只有两个可能的值具有值,如何使用 Terraform 实现这一点。我要复制的 CloudFormation 脚本是:
"ParameterName": {
"Description": "desc",
"Type": "String",
"Default": true,
"AllowedValues": [
"true",
"false"
]
}
我不知道
官方方法,但是在Terraform问题中描述了一种有趣的技术:
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 0.13 中提供自定义验证规则:
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."
}
}
自定义验证规则绝对是要走的路。如果您想保持简单并根据有效值列表检查提供的值,您可以在variables.tf
配置中使用以下命令:
variable "environment" {
type = string
description = "Deployment environment"
validation {
condition = contains(["dev", "prod"], var.environment)
error_message = "Valid value is one of the following: dev, prod."
}
}
上述答案使用数组/列表的变体。
variable "appservice_sku" {
type = string
description = "AppService Plan SKU code"
default = "P1v3"
validation {
error_message = "Please use a valid AppService SKU."
condition = can(regex(join("", concat(["^("], [join("|", [
"B1", "B2", "B3", "D1", "F1",
"FREE", "I1", "I1v2", "I2", "I2v2",
"I3", "I3v2", "P1V2", "P1V3", "P2V2",
"P2V3", "P3V2", "P3V3", "PC2",
"PC3", "PC4", "S1", "S2", "S3",
"SHARED", "WS1", "WS2", "WS3"
])], [")$"])), var.appservice_sku))
}
}