Module 4: Terraform Configuration

Lab 4C: Custom Conditions

Time
20 min
Cost
$0
Prerequisites
None listed
Objectives
0 of 5 checked

Starting file

Create ~/tf-course/lab4c/main.tf:

~/tf-course/lab4c/main.tfHCL
terraform {
  required_version = "~> 1.12.0"

  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.5"
    }
  }
}

variable "environment" {
  type = string

  validation {
    condition     = contains(["dev", "stage", "prod"], var.environment)
    error_message = "environment must be dev, stage, or prod."
  }
}

variable "replicas" {
  type    = number
  default = 1

  validation {
    condition     = var.environment != "prod" || var.replicas >= 3
    error_message = "prod requires at least 3 replicas."
  }
}

resource "local_file" "config" {
  filename = "${path.module}/app.conf"
  content  = "environment = ${var.environment}\nreplicas = ${var.replicas}\n"

  lifecycle {
    precondition {
      condition     = var.replicas <= 5
      error_message = "This host supports at most 5 replicas."
    }
    postcondition {
      condition     = length(self.content) < 100
      error_message = "Rendered config is unexpectedly large."
    }
  }
}

check "config_file_health" {
  data "local_file" "rendered" {
    filename = local_file.config.filename
  }

  assert {
    condition     = strcontains(data.local_file.rendered.content, "replicas")
    error_message = "Rendered config is missing the replicas setting."
  }
}

Steps

Shell
cd ~/tf-course/lab4c && terraform init

Command
terraform plan -var environment=qa
Expected result
Error: environment must be dev, stage, or prod.
Lesson
Validation blocks the run

Command
terraform plan -var environment=prod
Expected result
Error: prod requires at least 3 replicas.
Lesson
Cross-variable validation (1.9+)

Command
terraform plan -var environment=dev -var replicas=7
Expected result
Error: precondition failed: at most 5 replicas
Lesson
Precondition blocks the run

Command
terraform apply -auto-approve -var environment=prod -var replicas=3
Expected result
Apply succeeds. The check passes.
Lesson
Everything is satisfied

Command
Change the assert condition to look for "timeout", then apply again with the same variables
Expected result
Apply completes, with a warning that the check config_file_health failed
Lesson
check blocks only warn

Cleanup

Shell
terraform destroy -auto-approve -var environment=prod -var replicas=3

Lab 4C complete. Every step is checked.

This lab has no verification checklist in the course file, so it counts as complete when every step is checked.