Bird
Raised Fist0
Terraformcloud~5 mins

Check blocks for assertions in Terraform - Commands & Configuration

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Sometimes you want to make sure your infrastructure settings meet certain rules before creating resources. Check blocks in Terraform help you do this by stopping the process if conditions are not met.
When you want to ensure a variable value is within a safe range before applying changes.
When you need to prevent deployment if a required input is missing or incorrect.
When you want to enforce naming conventions for resources automatically.
When you want to avoid creating resources in unsupported regions.
When you want to catch configuration mistakes early to save time and avoid errors.
Config File - main.tf
main.tf
terraform {
  required_version = ">= 1.2.0"
}

variable "environment" {
  type    = string
  default = "dev"
}

variable "instance_count" {
  type    = number
  default = 2
}

check "valid_environment" {
  condition     = contains(["dev", "staging", "prod"], var.environment)
  error_message = "The environment must be one of: dev, staging, prod."
}

check "valid_instance_count" {
  condition     = var.instance_count > 0 && var.instance_count <= 5
  error_message = "Instance count must be between 1 and 5."
}

resource "null_resource" "example" {
  count = var.instance_count
}

terraform block: Specifies the required Terraform version.

variable blocks: Define inputs for environment and instance count.

check blocks: These are assertions that stop deployment if conditions are false. They include a condition and an error message.

resource block: Creates a number of dummy resources based on instance_count.

Commands
Initializes the Terraform working directory and downloads necessary providers.
Terminal
terraform init
Expected OutputExpected
Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/null... - Installing hashicorp/null v3.1.0... - Installed hashicorp/null v3.1.0 (signed by HashiCorp) Terraform has been successfully initialized! You may now begin working with Terraform. Try running "terraform plan" to see any changes that are required for your infrastructure.
Checks the configuration files for syntax errors and validates check blocks conditions.
Terminal
terraform validate
Expected OutputExpected
Success! The configuration is valid.
Applies the configuration to create resources. It will stop if any check block condition fails.
Terminal
terraform apply -auto-approve
Expected OutputExpected
null_resource.example[0]: Creating... null_resource.example[0]: Creation complete after 0s [id=123456] null_resource.example[1]: Creating... null_resource.example[1]: Creation complete after 0s [id=789012] Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
-auto-approve - Skips interactive approval before applying changes
Attempts to apply with an invalid environment variable, triggering a check block error.
Terminal
terraform apply -auto-approve -var='environment=invalid'
Expected OutputExpected
│ Error: Check failed: valid_environment │ with check.valid_environment, │ on main.tf line 13: │ 13: check "valid_environment" { │ The environment must be one of: dev, staging, prod.
-var - Overrides variable values from the command line
-auto-approve - Skips interactive approval before applying changes
Key Concept

If you remember nothing else from this pattern, remember: check blocks stop Terraform from applying changes when important conditions are not met.

Common Mistakes
Writing check conditions that always evaluate to true or false without testing.
This defeats the purpose of validation and can cause unexpected failures or no validation at all.
Test your check conditions with different variable values to ensure they behave as expected.
Not providing clear error_message in check blocks.
Users won't understand why the deployment failed, making troubleshooting harder.
Write simple, clear error messages that explain what is wrong and how to fix it.
Using check blocks in Terraform versions older than 1.2.0.
Check blocks are supported starting from Terraform 1.2.0, so older versions will fail to parse them.
Ensure your Terraform version is 1.2.0 or newer before using check blocks.
Summary
Use check blocks in Terraform to enforce rules before creating resources.
Run 'terraform validate' to check configuration syntax and conditions.
If a check condition fails, Terraform stops and shows your error message.

Practice

(1/5)
1. What is the main purpose of a check block in Terraform?
easy
A. To define variables for resource configuration
B. To verify conditions before resource creation and prevent errors
C. To output resource attributes after deployment
D. To create loops for multiple resource instances

Solution

  1. Step 1: Understand the role of check blocks

    Check blocks are used to verify conditions before Terraform creates resources to avoid invalid configurations.
  2. Step 2: Differentiate from other blocks

    Variables define inputs, outputs show results, and loops create multiple resources; none verify conditions before creation.
  3. Final Answer:

    To verify conditions before resource creation and prevent errors -> Option B
  4. Quick Check:

    Check blocks = pre-creation validation [OK]
Hint: Check blocks catch errors before deployment [OK]
Common Mistakes:
  • Confusing check blocks with variable declarations
  • Thinking check blocks output values
  • Assuming check blocks create resources
2. Which of the following is the correct syntax for a check block in Terraform?
easy
A. check "valid_region" { condition var.region == "us-east-1" error_message "Region must be us-east-1" }
B. check "valid_region" { assert = var.region == "us-east-1" message = "Region must be us-east-1" }
C. check "valid_region" { condition = var.region = "us-east-1" error = "Region must be us-east-1" }
D. check "valid_region" { condition = var.region == "us-east-1" error_message = "Region must be us-east-1" }

Solution

  1. Step 1: Identify correct attribute names

    The correct syntax uses condition for the boolean check and error_message for the error text.
  2. Step 2: Check syntax correctness

    check "valid_region" { condition = var.region == "us-east-1" error_message = "Region must be us-east-1" } correctly uses condition = and error_message = with proper equality ==. Others use wrong attribute names or syntax errors.
  3. Final Answer:

    check "valid_region" { condition = var.region == "us-east-1" error_message = "Region must be us-east-1" } -> Option D
  4. Quick Check:

    Use condition and error_message with equals signs [OK]
Hint: Use 'condition =' and 'error_message =' inside check blocks [OK]
Common Mistakes:
  • Using single equals (=) instead of double equals (==) for condition
  • Using wrong attribute names like assert or error
  • Missing equals signs between keys and values
3. Given this Terraform snippet:
variable "count" { type = number default = 3 }
check "positive_count" { condition = var.count > 0 error_message = "Count must be positive" }

What happens if you set count = 0 and run terraform apply?
medium
A. Terraform fails with error: Count must be positive
B. Terraform applies resources with count 0, creating none
C. Terraform ignores the check block and applies resources
D. Terraform applies resources but warns about count

Solution

  1. Step 1: Understand the check block condition

    The check block requires var.count > 0. Setting count = 0 violates this condition.
  2. Step 2: Predict Terraform behavior on violation

    Terraform stops and shows the error message from the check block instead of applying resources.
  3. Final Answer:

    Terraform fails with error: Count must be positive -> Option A
  4. Quick Check:

    Check blocks stop apply if condition false [OK]
Hint: Check blocks block apply if condition is false [OK]
Common Mistakes:
  • Thinking Terraform ignores check blocks
  • Assuming resources apply with warnings
  • Confusing default variable values with overrides
4. This Terraform check block causes an error during plan:
check "valid_name" { condition = var.name != "" error_message = "Name cannot be empty" }

What is the likely cause if var.name is not set?
medium
A. Terraform errors because var.name is null and comparison fails
B. Terraform ignores the check block if variable is unset
C. Terraform treats unset variable as empty string and passes check
D. Terraform applies default empty string and shows warning only

Solution

  1. Step 1: Analyze variable unset behavior

    If var.name is not set and has no default, it is null, not an empty string.
  2. Step 2: Understand condition evaluation

    Comparing null to empty string with != causes an error because null is not a string.
  3. Final Answer:

    Terraform errors because var.name is null and comparison fails -> Option A
  4. Quick Check:

    Null variables cause check block errors if compared to strings [OK]
Hint: Unset variables are null, not empty strings [OK]
Common Mistakes:
  • Assuming unset variables default to empty strings
  • Expecting check blocks to ignore null values
  • Thinking Terraform only warns on check failures
5. You want to enforce that a variable region is either "us-east-1" or "us-west-2" using a check block. Which is the correct check block to enforce this?
hard
A. check "valid_region" { condition = var.region == "us-east-1" || var.region == "us-west-2" error_message = "Region must be us-east-1 or us-west-2" }
B. check "valid_region" { condition = var.region == ["us-east-1", "us-west-2"] error_message = "Region must be us-east-1 or us-west-2" }
C. check "valid_region" { condition = contains(["us-east-1", "us-west-2"], var.region) error_message = "Region must be us-east-1 or us-west-2" }
D. check "valid_region" { condition = var.region in ("us-east-1", "us-west-2") error_message = "Region must be us-east-1 or us-west-2" }

Solution

  1. Step 1: Understand how to check membership in a list

    Terraform uses the contains(list, value) function to check if a value is in a list.
  2. Step 2: Evaluate each option

    check "valid_region" { condition = var.region == "us-east-1" || var.region == "us-west-2" error_message = "Region must be us-east-1 or us-west-2" } uses logical OR correctly but is verbose; check "valid_region" { condition = var.region == ["us-east-1", "us-west-2"] error_message = "Region must be us-east-1 or us-west-2" } compares a string to a list incorrectly; check "valid_region" { condition = contains(["us-east-1", "us-west-2"], var.region) error_message = "Region must be us-east-1 or us-west-2" } uses contains properly; check "valid_region" { condition = var.region in ("us-east-1", "us-west-2") error_message = "Region must be us-east-1 or us-west-2" } uses invalid syntax in.
  3. Final Answer:

    check "valid_region" { condition = contains(["us-east-1", "us-west-2"], var.region) error_message = "Region must be us-east-1 or us-west-2" } -> Option C
  4. Quick Check:

    Use contains(list, value) to check membership [OK]
Hint: Use contains() to check if value is in list [OK]
Common Mistakes:
  • Using 'in' keyword which Terraform does not support
  • Comparing string directly to list
  • Using verbose OR instead of contains()