Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Terraform Cookbook

You're reading from   Terraform Cookbook Master Infrastructure as Code efficiency with real-world Azure automation using Terraform

Arrow left icon
Product type Paperback
Published in Aug 2023
Publisher Packt
ISBN-13 9781804616420
Length 634 pages
Edition 2nd Edition
Tools
Concepts
Arrow right icon
Author (1):
Arrow left icon
Mikael Krief Mikael Krief
Author Profile Icon Mikael Krief
Mikael Krief
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface 1. Setting Up the Terraform Environment 2. Writing Terraform Configurations FREE CHAPTER 3. Scaling Your Infrastructure with Terraform 4. Using Terraform with External Data 5. Managing Terraform State 6. Applying a Basic Terraform Workflow 7. Sharing Terraform Configuration with Modules 8. Provisioning Azure Infrastructure with Terraform 9. Getting Starting to Provisioning AWS and GCP Infrastructure Using Terraform 10. Using Terraform for Docker and Kubernetes Deployment 11. Running Test and Compliance Security on Terraform Configuration 12. Deep-Diving into Terraform 13. Automating Terraform Execution in a CI/CD Pipeline 14. Using Terraform Cloud to Improve Team Collaboration 15. Troubleshooting Terraform Errors 16. Other Books You May Enjoy
17. Index
Appendix A: Terraform Cheat Sheet 1. Appendix B: Terraform Resources

Adding custom pre and postconditions

In a previous recipe, Manipulating variables, we learned that it is possible to add condition validation inside the variable definition.

In Terraform version 1.2 and newer, it’s possible to add custom validation directly in resources, modules, or data sources with preconditions and postconditions.

These customs validations allow Terraform to set some custom rules during the execution of terraform plan. The precondition will be checked just before the rendering of the plan and the postcondition will be checked just after the rendering.

Let’s get started!

Getting ready

To complete this recipe, we will start with this basic Terraform configuration:

resource "azurerm_virtual_network" "vnet" {
  name                = "vnet"
  location            = azurerm_resource_group.rg.location
  resource_group_name = azurerm_resource_group.rg.name
  address_space       =  [var.address_space] 
}

The above Terraform configuration creates an Azure virtual network.

The first check that we want to perform is to be sure that the address_space variable’s value is IP mask /16.

The second check is to verify that the region (location) of the virtual network is "westeurope".

The source code of this recipe is available at https://github.com/PacktPublishing/Terraform-Cookbook-Second-Edition/tree/main/CHAP02/prepostcond.

How to do it…

The following step shows you how to perform the first check, which is the verification of the IP address range:

  1. Update the Terraform configuration of the Azure virtual network with the code below:
    resource "azurerm_virtual_network" "vnet" {
    …..
      address_space       =  [var.address_space]
      lifecycle {
        precondition {
          condition = cidrnetmask(var.address_space) == "255.255.0.0"
          error_message = "The IP Range must be /16"
        }
      }
    }
    
  2. Then, add the second check to verify the location by adding this configuration in the Azure virtual network:
    resource "azurerm_virtual_network" "vnet" {
      name                = "vnet"
      location            = azurerm_resource_group.rg.location
      resource_group_name = azurerm_resource_group.rg.name
      address_space       =  [var.address_space]
      lifecycle {
        precondition {
          condition = cidrnetmask(var.address_space) == "255.255.0.0"
          error_message = "The IP Range must be /16"
        }
        postcondition {
          condition = self.location  == "westeurope"
          error_message = "Location must be westeurope"
        }
      }
    }
    
  3. Finally, run the Terraform workflow and check that no Terraform error is displayed in the console output.

How it works…

In Step 1, we added the first custom check, which corresponds to the precondition that will be run just before the plan. The precondition block is new inside the lifecycle block metadata. Let’s see this precondition in detail:

precondition {
      condition = cidrnetmask(var.address_space) == "255.255.0.0"
      error_message = "The IP Range must be /16"
}

The precondition block contains two properties:

  1. The condition, that is, the code for the check. Here, we check that the cidrmask of the value of the address_mask variable is equal to “255.255.0.0", that is, that the IP range is /16.
  2. The error_message, that is, the error message that is displayed in the console output if the check returns false.

To test this precondition, if we set the value of the address_space variable to "10.0.0.0/24", the terraform plan execution returns this output:

Une image contenant texte  Description générée automatiquement

Figure 2.18: Precondition custom validation error

The error message is displayed and the terraform plan command doesn’t continue.

Then in Step 2, we add the check for testing the region (the data center’s location) of the Azure virtual network, which must be equal to “westeurope". To do this, we add a postcondition block inside the lifecycle metadata with the following configuration:

postcondition {
      condition = self.location  == "westeurope"
      error_message = "Location must be West Europe"
}

In the configuration above, we set the condition property by using the self keyword to refer to the current resource (in this case this is the Azure virtual network) and we set the error message.

Note that the self keyword can be used only on postconditions, at the moment that all properties are determined, which is only after the terraform plan command has been run.

To test this postcondition, we set the location to "westus" and we get this terraform plan output:

Une image contenant texte  Description générée automatiquement

Figure 2.19: Postcondition custom validation error

We can see that the error message is displayed.

See also

You have been reading a chapter from
Terraform Cookbook - Second Edition
Published in: Aug 2023
Publisher: Packt
ISBN-13: 9781804616420
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime