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:

Terraform object type constraints project example

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 which is of type number.

Object definition#

To define the object, we specify each field inside {} brackets. Each field has the form fieldname = type. Here, we are giving a person some default values. If you run this project, you will see that the person output will contain the values we gave it; Bob, 10.

These values are limited to the types we define, so if you tried to assign a string to the age field, you would get a type constraint error. One interesting thing to point out is that you can have different items with the same name in Terraform.

In this project, we have a variable with the identifier “person”, and we have an output with the same identifier. This is allowed because one is a variable and the other is output. You are not allowed to have two variables with the same identifier or two outputs.

Building complex structures#

Next, we are defining a variable called person_with_address to show how you can nest objects to build up even more complex structures. The person structure is the same as before, except we have added the field address. The field address is in itself an object which contains four strings.

  • line1
  • line2
  • county
  • postcode

You can see when we initialise the variable. We set the address by wrapping the values in a set of {} brackets. When you run the project, you will see the person_with_address structure printed out.

By using the same technique as above, you can build up complex structures.

Running the project#

Clicking the terminal will run terraform init and terraform apply commands. When prompted, type yes and press enter.

This code requires the following environment variables to execute:
access_key_id
Not Specified...
secret_access_key
Not Specified...
Terminal 1
Terminal

Click to Connect...

📝Note: Once you are done with the project, do not forget to run terraform destroy and then confirm with yes to delete all of the resources in this project.

Type Constraints - Map
Type constraints - Any Type
Mark as Completed
Report an Issue