More Complex Variables

In this lesson, we'll learn about some more complex Terraform variables.

We'll cover the following

Project example#

Let’s look at a more complex example using a map and selecting a value from it with variables:

This code requires the following environment variables to execute:
access_key_id
Not Specified...
secret_access_key
Not Specified...
/
terraform.tfvars
main.tf
Variables complex project example
  • In our variables file, we are setting instance_map to a map.

  • A map is a collection of values indexed by a key name. We have set three keys in our map

    • dev
    • test
    • prod
  • The values we have given for each of these keys are instance types to use in AWS.

  • This map could be used to set the instance size based on the type of environment we are creating.

  • Next, we are setting the environment_type variable to dev.

    If you look at the Terraform code we have written, you will see that we are defining the two variables instance_map and environment_type.

  • At the bottom, we are outputting the value in the map for the key specified by the environment_type variable.

Running the project#

If you run this project as is, it will output selected_instance = t3.small. This is because t3.small is the value in the map for the key dev and we have set the environment_type to dev. Change the environment type to one of the other values in the map, run the project again, and you will see the output change


Since the map of instances is a variable, we could dynamically change this too. For instance, we could have a different terraform.tfvars file per department for example. This allows us to vary the instance sizes used for different environment types by the department.

📝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.

Setting a Variable Using a File
Type Constraints - Simple Types
Mark as Completed
Report an Issue