skip to Main Content

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


  1. 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}]
    

    Example:

    Example

    Login or Signup to reply.
  2. 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
    ...
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search