【问题标题】:Terraform - validate a variable based on another variable?Terraform - 基于另一个变量验证一个变量?
【发布时间】:2023-01-20 02:26:43
【问题描述】:
假设我有一个用于创建 AWS EC2 实例的 Terraform 模块。
现在,我希望用户能够使用默认 VPC,或提供另一个 VPC ID。
所以我定义了以下输入变量:
# variables.tf
variable "default_vpc" {
description = "Whether or not deploy the instance in the default VPC"
type = bool
}
variable "vpc_id" {
description = "VPC ID to deploy the instance in"
type = string
default = ""
}
现在,如果用户将 false 传递给 default_vpc,我想确保他确实在 vpc_id 中传递了一些值。那可能吗?
【问题讨论】:
标签:
amazon-web-services
terraform
【解决方案1】:
您可以像这样将其声明为布尔映射:
variable "vpc_id" {
type = map(bool)
default = {
true = "default_vpc is true"
false = "default_vpc is false"
}
}
现在你可以像这样使用它:
var.vpc_id[${var.default_vpc}]
【解决方案2】:
虽然无法使用 input variable validation 来实现,但根据 Terraform 版本,您可以使用 preconditions。
resource "null_resource" "vpc_precondition_validation" {
lifecycle {
precondition {
condition = (var.default_vpc == false && var.vpc_id != "") || (var.default_vpc == true && var.vpc_id == "")
error_message = "There has been error while validating the inputs for default_vpc and vpc_id variables."
}
}
}
在这种情况下,当我们为变量 default_vpc 输入 false 并且我们没有为 vpc_id 变量提供值时,它将打印错误消息。
当default_vpc 设置为 true 时,它将允许 vpc_id 变量为空字符串。