Validating the code

Along the same lines, Terraform has a command that validates the code and allows us to detect possible errors before executing the plan or apply command.

Let's take the example of this code extract:

resource "azurerm_public_ip" "pip" {
name = var.ip-name
location = var.location
resource_group_name = "${azurerm_resource_group.rg.name}"
allocation_method = "Dynamic"
domain_name_label = "bookdevops"
}

In the name property, we use an ip-name variable that has not been declared or instantiated with any value.

Executing the terraform plan command would return an error:

And because of this error, in a CI/CD process, it could delay the deployment of the infrastructure.

In order to detect errors in the Terraform code as early as possible in the development cycle, execute the following command, which validates all Terraform files in the directory:

terraform validate

The following screenshot shows the execution of this command:

We observe the same error as the one returned by the plan command.

We have just seen Terraform's main command lines. Let's go a little deeper with the integration of Terraform into a CI/CD process.