Type constraints - Object

We will learn how to use Object type constraints in your Terraform project.

Object

An object is a structure that you can define from the other types listed above. They allow you to define quite complex objects and constrain them to types. The easiest way to explain this is to dive straight into an example.

Project example

Consider the following project example:

Press + to interact
variable "person" {
type = object({ name = string, age = number })
default = {
name = "Bob"
age = 10
}
}
output "person" {
value = var.person
}
variable "person_with_address" {
type = object({ name = string, age = number,
address = object({ line1 = string, line2 = string,
county = string, postcode = string }) })
default = {
name = "Jim"
age = 21
address = {
line1 = "1 the road"
line2 = "St Ives"
county = "Cambridgeshire"
postcode = "CB1 2GB"
}
}
}
output "person_with_address" {
value = var.person_with_address
}

In the project above, we first define a variable called person. This variable has two fields:

  • a name which is of type string and

  • an age ...