Crafting Reliable Terraform Configuration via Custom Conditions, Checks, and Variable Validation

Ivan (이반) Porta
7 min readSep 28, 2023

--

In this article, we explore Terraform’s pre/post conditions, check blocks, and variable validation, equipping developers with practical examples for crafting reliable and efficient configurations.

Lifecycle Preconditions and Postconditions

Introduced in Terraform 1.2.0, the lifecycle precondition and postcondition blocks can be attached to resource, data source, or output blocks. During the planning and applying phases, Terraform evaluates these conditions. If any condition fails, Terraform interrupts the plan or apply process.

  • Preconditions: Evaluated before provisioning the enclosing block.
  • Postconditions: Evaluated after provisioning.
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "training" {
name = "rg-training-neu-01"
location = "northeurope"
}
resource "azurerm_app_service_plan" "training" {
name = "asp-training-neu-01"
location = azurerm_resource_group.training.location
resource_group_name = azurerm_resource_group.training.name
sku {
tier = "Standard"
size = "S1"
}
}
resource "azurerm_app_service" "training" {
name = "as-training-neu-01"
location = azurerm_resource_group.training.location
resource_group_name = azurerm_resource_group.training.name
app_service_plan_id = azurerm_app_service_plan.training.id
}
resource "azurerm_app_service_certificate" "training" {
name = "cert-sample-neu-01"
resource_group_name = azurerm_resource_group.training.name
location = azurerm_resource_group.training.location
pfx_blob = filebase64("certificate.pfx")
password = "YourPassword"
lifecycle {
precondition {
condition = azurerm_resource_group.training.location == "uksouth"
error_message = "Certificate must be created in the 'uksouth' region."
}
postcondition {
condition = self.issuer == "jhon.doe@outlook.com"
error_message = "Certificate issuer must be jhon.doe@outlook.com."
}
}

}

In the example above, I’ve set a precondition to ensure the app service certificate is going to be…

--

--

Ivan (이반) Porta

Microsoft Certified DevOps Engineer Expert | MCT | MCE | Public Speaker