Skip to main content
InterviewHubPRO
Section Overview
Q18

Question 18 of 50

Part 2: Modules, Multi-Environment & GitOps (16 - 30)

36%
Terraform & IaC (50 Qs)•Part 2: Modules, Multi-Environment & GitOps (16 - 30)

How do Custom Input Validation, Preconditions, and Postconditions work in Terraform?

mid LevelCode ExampleFormsCI/CD & DevOpsTerraform & IaC

In Simple Words:

  • Variable Validation: Enforces input constraints at plan time.
  • Preconditions: Assertions verified before a resource or module evaluates.
  • Postconditions: Assertions verified after a resource is created, checking real cloud attributes.
hcl
variable "db_instance_class" {
  type = string
  validation {
    condition     = can(regex("^db\.m6i\.", var.db_instance_class))
    error_message = "Only production-approved db.m6i instance classes are allowed."
  }
}

resource "aws_ebs_volume" "data" {
  availability_zone = "us-east-1a"
  size              = 100

  lifecycle {
    postcondition {
      condition     = self.encrypted == true
      error_message = "EBS volume MUST be encrypted."
    }
  }
}