0
0
Terraformcloud~15 mins

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

Choose your learning style9 modes available
Terraform Variable Validation Rules
📖 Scenario: You are setting up a Terraform configuration to deploy cloud resources. To avoid mistakes, you want to add rules that check if the input variables meet certain conditions before applying the configuration.
🎯 Goal: Create a Terraform variable with validation rules that ensure the input is a string with a length between 3 and 10 characters.
📋 What You'll Learn
Define a variable named environment of type string
Add a validation block that checks the length of environment is at least 3 characters
Add a validation block that checks the length of environment is at most 10 characters
Provide a custom error message if the validation fails
💡 Why This Matters
🌍 Real World
Terraform variable validation helps prevent mistakes by checking user inputs before deploying cloud infrastructure, saving time and avoiding errors.
💼 Career
Cloud engineers and DevOps professionals use variable validation to create reliable and user-friendly Terraform modules and configurations.
Progress0 / 4 steps
1
Create the environment variable
Create a Terraform variable named environment of type string.
Terraform
Need a hint?

Use the variable block with the name environment and set type = string.

2
Add minimum length validation
Add a validation block inside the environment variable that checks if the length of var.environment is at least 3 characters using length(var.environment) >= 3.
Terraform
Need a hint?

Use a validation block with condition and error_message inside the variable.

3
Add maximum length validation
Add another validation block inside the environment variable that checks if the length of var.environment is at most 10 characters using length(var.environment) <= 10. Keep the previous validation block as well.
Terraform
Need a hint?

Add a second validation block with the maximum length condition and error message.

4
Complete the variable with both validations
Ensure the environment variable block includes both validation blocks for minimum and maximum length with their respective error messages.
Terraform
Need a hint?

Review the entire variable block to confirm both validations are present.