Debugging/Logging in Terraform

terraform
Reading Time: 2 minutes

Debugging is a very important part of developers’ life as it helps in understanding the root cause whenever any piece of code breaks! So, In this blog, we will understand how to set up the debugging while setting up an Infrastructure using terraform.

Prerequisite

  • Basic knowledge of Terraform

Enable Debugging in Terraform!

Terraform provides the options to enable detailed logging/debugging with the help of the TF_LOG environment variable.
It provides the option to set TF_LOG to various different log levels: TRACEDEBUGINFOWARN or ERROR.

  • TRACE: Very detailed verbosity, shows every step taken by Terraform, and produces enormous outputs with internal logs.
  • DEBUG: describes what happens internally in a more concise way compared to TRACE.
  • ERROR: shows errors that prevent Terraform from continuing.
  • WARN: logs warnings, which may indicate misconfiguration or mistakes, but are not critical to the execution.
  • INFO: shows general, high-level messages about the execution process.

To persist the generated logs you need to set the TF_LOG_PATH environment variable in order to force the log to always be appended to a specific file when logging is enabled.

Demo!

I have simply put two terraform configurations files in my directory to create an ec2 instance.

c1-versions.tf file contains the following code:

provider “aws” {
region = “us-east-1”
}

ec2-instance.tf file contains the following code:

resource "aws_instance" "my-ec2-vm" {
  ami               = "ami-047a51fa27710816e"
  instance_type     = "t2.micro"
  availability_zone = "us-east-1a"
  tags = {
    "Name" = "web"
  }
}

Now to enable the logging, let’s export the TF_LOG and TF_LOG_PATH Environment variables.

Now let’s see the logging in action!

Let’s Initialize the directory by running terraform init and apply the configurations by running the terraform apply command.

So, we can see a file with the name terraform-trace.log is generated after applying the terraform configurations.

This file will contain all the detailed logs related to terraform.

Conclusion

In Conclusion, In this blog, we learned how we can enable logging and debugging in terraform to troubleshoot the issues we might face while deploying the infrastructure using terraform.
Happy Learning!

Resources

https://www.terraform.io/internals/debugging

knoldus

Written by 

DevOps Engineer at Knoldus. Loves to solve new problems. Always eager to learn new technologies.