Skip to main content

Implementing Check Blocks

1. Declaring Check Blocks

Property Description Values Notes
check Defines a check block check Used to define assertions about the state of resources or data sources
name Unique identifier for the check block string Required field to distinguish checks in logs and reports
condition Boolean expression to evaluate string Must resolve to a boolean value; can reference attributes of resources or data sources
error_message Message to display if the check fails string Optional; helps in debugging and understanding why a check failed

Example: Basic Check Block

check "valid_instance_type" {
  condition     = aws_instance.example.instance_type == "t3.micro"
  error_message = "The instance type must be t3.micro"
}

2. Defining Check Assertions

Property Description Values Notes
check Defines a check block check "assertion_name" { ... } Used to define assertions that must pass for the configuration to be valid

Example: Basic Check Assertion

check "valid_instance_type" {
  assert {
    condition     = aws_instance.example.instance_type != "t2.micro"
    error_message = "Instance type must not be t2.micro"
  }
}

Example: Check with Multiple Conditions

check "resource_compliance" {
  assert {
    condition     = aws_instance.example.instance_type == "t3.medium"
    error_message = "Instance type must be t3.medium"
  }

  assert {
    condition     = aws_instance.example.ami != ""
    error_message = "AMI must be specified"
  }
}
Note: Check blocks are evaluated during terraform plan and terraform apply. If any assertion fails, the operation will be halted.

3. Configuring Check Scoped Data Sources

Property Description Values Notes
check.name Name of the check block string Required for all check blocks
check.description Human-readable description of the check string Optional but recommended
check.assertion Boolean expression to evaluate string Must resolve to a boolean value
check.error_message Error message if assertion fails string Optional, defaults to assertion failure

Example: Basic Check Block Configuration

check "valid_instance_type" {
  assert {
    condition     = var.instance_type != "t2.micro"
    error_message = "Instance type t2.micro is not allowed"
  }
}

Example: Using Data Sources in Checks

data "aws_instance" "web" {
  instance_id = aws_instance.web.id
}

check "instance_has_required_tags" {
  assert {
    condition = length(data.aws_instance.web.tags) > 0
    error_message = "Instance must have at least one tag"
  }
}
Note: Check blocks can reference data sources defined in the same configuration, allowing for validation of computed or external values.

4. Using Conditions in Checks

Condition Type Description Example
check Defines a condition to be evaluated
check {
  condition = aws_instance.web.private_ip != null
  description = "Web instance must have a private IP"
}
condition Boolean expression to evaluate condition = var.instance_count > 0
description Human-readable description of the check description = "Ensure all instances are running"

Example: Conditional Check with Variables

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

check {
  condition = var.instance_count > 0
  description = "Instance count must be greater than zero"
}

Example: Check with Resource Attributes

resource "aws_instance" "web" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"
}

check {
  condition = aws_instance.web.private_ip != null
  description = "Web instance must have a private IP address"
}

5. Adding Error Messages

Example: Basic Error Message in Check Block

check {
  source = "./checks"
  error_message = "The instance type must be t3.micro or t3.small"
}
Attribute Description Required
error_message Custom error message to display when the check fails Yes
Note: The error_message attribute is required for all check blocks to provide clear feedback when validation fails.

6. Running Continuous Validation

Example: Continuous Validation with Terraform Cloud

terraform validate
Command Description Notes
terraform validate Validates the Terraform configuration files Checks syntax and performs static analysis
terraform plan Generates and displays the execution plan Shows what changes will be made to infrastructure
Note: Continuous validation helps ensure that infrastructure changes are safe and compliant before they are applied.
Warning: Running terraform validate does not apply changes to infrastructure; it only checks the configuration.

Key Points

  • terraform validate checks the syntax and correctness of Terraform configuration files.
  • It ensures that all variables, resources, and data sources are properly defined.
  • Validation can be run locally or integrated into CI/CD pipelines for automated checks.

7. Comparing Checks vs Preconditions

Feature Checks Preconditions
Purpose Validate resource configuration values Validate input values before resource creation
When Evaluated During plan and apply phases During plan phase only
Scope Resource-level validation Input variable-level validation
Error Handling Failures halt deployment Failures halt deployment
Use Case Example
resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = var.instance_type

  check "valid_instance_type" {
    condition     = contains(["t2.micro", "t3.micro"], self.instance_type)
    error_message = "Only t2.micro and t3.micro instance types are allowed."
  }
}
variable "instance_type" {
  type = string

  validation {
    condition     = contains(["t2.micro", "t3.micro"], var.instance_type)
    error_message = "Only t2.micro and t3.micro instance types are allowed."
  }
}

Key Differences Summary

  • Checks are evaluated during both plan and apply, while Preconditions only during plan.
  • Checks validate resource configurations, while Preconditions validate input variables.
  • Checks provide more granular control over validation timing, while Preconditions offer early input validation.

8. Handling Check Failures

Example: Using assert to fail checks

resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.micro"

  check "instance_size" {
    condition     = self.instance_type != "t3.micro"
    error_message = "Instance type must not be t3.micro"
  }
}
Property Description Notes
condition Boolean expression to evaluate Must return true or false
error_message Message to display when check fails Required if check fails
name Name of the check block Optional, used for reference
Note: Check blocks are evaluated during plan and apply phases. If a check fails, the operation will be halted.
Warning: Checks are not enforced in the state file, they only affect plan and apply.

Check Failure Handling Summary

  • Use condition to define the check logic
  • Provide error_message for clarity on failure reason
  • Checks halt execution if they fail
  • Checks are not stored in state, only validated at runtime

9. Using Checks for Drift Detection

Checks in Terraform can be used to detect configuration drift by comparing the current state of resources with their expected configuration.

Property Description Example
check Defines a check block to validate resource attributes or state
check {
  name = "drift_check"
  condition = can(resource.aws_instance.example.id)
  error_message = "Resource drift detected"
}

Example: Drift Detection with Check Blocks

resource "aws_instance" "example" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"
}

check "drift_check" {
  name = "instance_drift_check"
  condition = can(resource.aws_instance.example.id)
  error_message = "Drift detected in aws_instance.example"
}
Note: Drift detection using checks is a proactive measure to ensure that your infrastructure remains aligned with the desired configuration.

10. Implementing Health Checks

Property Description Example
check Defines a health check block to monitor the status of resources
check "health_check" {
  assert {
    condition = aws_instance.web.status == "running"
    error_message = "Web instance is not running"
  }
}

Example: Basic Health Check

resource "aws_instance" "web" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"
}

check "web_instance_health" {
  assert {
    condition = aws_instance.web.status == "running"
    error_message = "Web instance is not running"
  }
}
Note: Health checks in Terraform are used to validate the state of resources after deployment.
Warning: Ensure that the condition in the assert block evaluates to a boolean value.

Was this article helpful?