0
0
Terraformcloud~30 mins

Variable validation blocks in Terraform - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Variable Validation Blocks in Terraform
📖 Scenario: You are setting up a Terraform configuration to create cloud resources. To make your configuration safer and easier to use, you want to add rules that check if the input variables have valid values before applying the changes.
🎯 Goal: Build a Terraform variable with a validation block that ensures the input meets specific rules, such as allowed values or ranges.
📋 What You'll Learn
Create a Terraform variable named environment with a description and type string.
Add a validation block to the environment variable that only allows the values "dev", "staging", or "prod".
Create a Terraform variable named instance_count with a description and type number.
Add a validation block to the instance_count variable that requires the value to be between 1 and 5 inclusive.
💡 Why This Matters
🌍 Real World
Variable validation blocks in Terraform help prevent mistakes by checking user inputs before creating cloud resources. This saves time and avoids costly errors.
💼 Career
Cloud engineers and DevOps professionals use Terraform variable validation to write safer infrastructure code that is easier to maintain and share.
Progress0 / 4 steps
1
Create the environment variable
Create a Terraform variable named environment with type string and description "Deployment environment".
Terraform
Need a hint?

Use the variable block with type and description fields.

2
Add validation to the environment variable
Add a validation block inside the environment variable that allows only the values "dev", "staging", or "prod". Use condition with contains and error_message to explain the rule.
Terraform
Need a hint?

The validation block uses condition to check if the variable value is in a list.

3
Create the instance_count variable
Create a Terraform variable named instance_count with type number and description "Number of instances to create".
Terraform
Need a hint?

Use a variable block with type = number and a description.

4
Add validation to the instance_count variable
Add a validation block inside the instance_count variable that requires the value to be between 1 and 5 inclusive. Use condition with comparison operators and error_message to explain the rule.
Terraform
Need a hint?

The validation block uses condition with comparison operators to check the range.