Say I have a Terraform module for creating a AWS EC2 instance.
Now, I want the user to be able to either use the default VPC, or provide another 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
. Is that possible?
2
Answers
You could be declaring it as a boolean map like this:
Now you could be using it like this:
Example:
While there’s no way to implement using input variable validation, depending on the Terraform version you can use preconditions.
In this case, when we input
false
for the variabledefault_vpc
and we don’t provide a value for thevpc_id
variable it’s going to print the error message.When
default_vpc
is set to true, it will allow thevpc_id
variable to be an empty string.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: