Home > front end >  Terraform - validate a variable based on another variable?
Terraform - validate a variable based on another variable?

Time:01-20

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?

CodePudding user response:

While there's no way to implement using input variable validation, depending on the Terraform version you can use 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."
    }
  }
}

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.

When default_vpc is set to true, it will allow the vpc_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:

...
vpc_id = var.default_vpc == false ? var.vpc_id : data.aws_vpc.default.id
...

CodePudding user response:

You could be declaring it as a boolean map like this:

variable "vpc_id" {
  type = map(bool)
  default = {
    true    = "default_vpc is true"
    false   = "default_vpc is false"
  }
}

Now you could be using it like this:

var.vpc_id[${var.default_vpc}]
  • Related