1. Object Variable

Instead of making separate variables for each value, you can group them into one object.

Like variables that configure the same resource or feature together.

For example:

Basically if removing one of them makes the others incomplete or useless, they belong together in an object.

Without object variable — separate variable for each value:

variable "volume_size" {
  type    = number
  default = 20
}

variable "volume_type" {
  type    = string
  default = "gp2"
}

# Use separately
volume_size = var.volume_size
volume_type = var.volume_type

With object variable — all related values in one place:

variable "ec2_config" {
  type = object({
    v_size = number
    v_type = string
  })
  default = {
    v_size = 20
    v_type = "gp2"
  }
}

# Access using dot notation
volume_size = var.ec2_config.v_size
volume_type = var.ec2_config.v_type

Pass via CLI:

terraform plan -var='ec2_config={v_size=50, v_type="gp2"}'

you can pass object variables the same ways as any other variable:

  1. CLIvar='ec2_config={v_size=50, v_type="gp2"}'
  2. terraform.tfvars — just write it directly:

hcl

   ec2_config = {
     v_size = 50
     v_type = "gp2"
   }