0
0
Terraformcloud~30 mins

Type constraints in variables in Terraform - Mini Project: Build & Apply

Choose your learning style9 modes available
Type constraints in variables
📖 Scenario: You are setting up a Terraform configuration to manage cloud resources. To avoid mistakes, you want to define variables with specific type constraints so that only valid values can be used.
🎯 Goal: Build a Terraform configuration that defines variables with type constraints and uses them in a resource configuration.
📋 What You'll Learn
Define a variable with a string type constraint
Define a variable with a list of strings type constraint
Define a variable with a map of numbers type constraint
Use the variables in a resource block
💡 Why This Matters
🌍 Real World
Defining variables with type constraints helps prevent errors when deploying cloud infrastructure by ensuring only valid data is used.
💼 Career
Cloud engineers and DevOps professionals use Terraform variable type constraints to write reliable and maintainable infrastructure code.
Progress0 / 4 steps
1
Define a string variable
Create a Terraform variable called region with type string and default value "us-west-1".
Terraform
Need a hint?

Use the variable block with type = string and set default to "us-west-1".

2
Define a list of strings variable
Add a Terraform variable called availability_zones with type list(string) and default value ["us-west-1a", "us-west-1b"].
Terraform
Need a hint?

Use list(string) as the type and set the default to the list of zones.

3
Define a map of numbers variable
Add a Terraform variable called instance_counts with type map(number) and default value { web = 2, db = 1 }.
Terraform
Need a hint?

Use map(number) as the type and set the default map with keys web and db.

4
Use variables in a resource
Create a Terraform resource aws_instance named web_server that uses the variable region for availability_zone and the variable instance_counts to set count to the value for key web.
Terraform
Need a hint?

Use count = var.instance_counts["web"] and availability_zone = var.region inside the resource block.