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:
db_host, db_port, db_name → all about the database → group into db_configvpc_cidr, subnet_cidr, region → all about networking → group into network_configbucket_name, bucket_region, versioning → all about S3 → group into s3_configBasically 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:
var='ec2_config={v_size=50, v_type="gp2"}'hcl
ec2_config = {
v_size = 50
v_type = "gp2"
}