DEV Community

Cover image for Type Constraints in Terraform
Sainath Patil
Sainath Patil

Posted on

Type Constraints in Terraform

As your modules grow in complexity, so does the need for strong type safety. Type constraints help you catch errors early, enforce structure, and write more predictable, maintainable Terraform code.

Why Type Constraints Matter

  • Fewer runtime errors
  • Easier debugging
  • Cleaner module interfaces
  • More reliable, reusable infrastructure code

Primitive (Basic Types)

String

  • Used for plain text values.
variable "env" {
  type = string
}
Enter fullscreen mode Exit fullscreen mode

Number

  • Represents integers or floating-point numbers.
variable "instance_count" {
  type = number
}

Enter fullscreen mode Exit fullscreen mode

Bool
Boolean values: true or false.

variable "enabled" {
  type = bool
}

Enter fullscreen mode Exit fullscreen mode

Complex (Collection Types)

list(type)
An ordered collection of elements of the same type.

variable "allowed_regions" {
  type = list(string)
}

Enter fullscreen mode Exit fullscreen mode

set(type)
An unordered, unique collection.

variable "security_groups" {
  type = set(string)
}

Enter fullscreen mode Exit fullscreen mode

map(type)
An unordered, unique collection.

variable "tags" {
  type = map(string)
}

Enter fullscreen mode Exit fullscreen mode

tuple([type1, type2, ...])
An ordered list where each element has a different type.

variable "config_tuple" {
  type = tuple([string, number, bool])
}

Enter fullscreen mode Exit fullscreen mode

object({ key = type })
A structured data object with named attributes, same as JSON

variable "network_config" {
  type = object({
    cidr_block = string
    subnets    = list(string)
    public     = bool
  })
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)