[英]Terraform - validate a variable based on another variable?
Say I have a Terraform module for creating a AWS EC2 instance.假设我有一个用于创建 AWS EC2 实例的 Terraform 模块。
Now, I want the user to be able to either use the default VPC, or provide another VPC ID.现在,我希望用户能够使用默认 VPC,或提供另一个 VPC ID。 So I define the following input variables:所以我定义了以下输入变量:
# 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 = ""
}
Now, in case the user passes false
for default_vpc
, I want to ensure that he does pass some value in vpc_id
.现在,如果用户为default_vpc
传递false
,我想确保他确实在vpc_id
中传递了一些值。 Is that possible?那可能吗?
While there's no way to implement using input variable validation , depending on the Terraform version you can use preconditions .虽然无法使用输入变量验证来实现,但根据 Terraform 版本,您可以使用先决条件。
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."
}
}
}
In this case, when we input false
for the variable default_vpc
and we don't provide a value for the vpc_id
variable it's going to print the error message.在这种情况下,当我们为变量default_vpc
输入false
并且我们没有为vpc_id
变量提供值时,它将打印错误消息。
When default_vpc
is set to true, it will allow the vpc_id
variable to be an empty string.当default_vpc
设置为 true 时,它将允许vpc_id
变量为空字符串。
Then in the resource where the vpc_id
is required, you can use a ternary condition, assuming the default vpc id attribute is retrieved from a data source:然后在需要vpc_id
的资源中,您可以使用三元条件,假设默认的 vpc id 属性是从数据源中检索到的:
...
vpc_id = var.default_vpc == false ? var.vpc_id : data.aws_vpc.default.id
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.