DEV Community

Arun Kumar Singh
Arun Kumar Singh

Posted on

Terraform: Good to know features - Post 1

Terraform Validation

Starting Terraform 0.13, Hashicorp has released Custom Variable Validation in HCL. Each variable block can have zero or more validation blocks and an error message. It's quite useful feature which gives you an edge to control the values.

variable "cloudenv" {
  type        = string
  description = "Cloud Environment"

  validation {
    condition = anytrue([
      var.cloudenv == "prd",
      var.cloudenv == "qa",
      var.cloudenv == "uat",
      var.cloudenv == "dev"
    ])
    error_message = "Must be a valid Cloud Env, values can be prd, qa, uat, or dev."
  }
}

Enter fullscreen mode Exit fullscreen mode

Terraform Suppressing Values

There are certain cases in which you want terraform not to print the information when you run plan or apply. Good part is terraform has a way for you. Setting a variable as sensitive prevents Terraform from showing its value in the plan or apply output.

variable "user_information" {
  type = object({
    name    = string
    address = string
  })
  sensitive = true
}
Enter fullscreen mode Exit fullscreen mode

Debug terraform

You can set TF_LOG to one of the log levels TRACE, DEBUG, INFO, WARN or ERROR to change the verbosity of the logs and push it to one of the files on disk for analysis.

mkdir logs
export TF_LOG_PATH="./logs/terraform.log"
export TF_LOG="INFO" 
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
dogers profile image
Dogers

Unless something has changed in TF 1.x, your first example won't work - "var.env" should be "var.cloudenv" as the validation can only reference the variable it's validating..

Collapse
 
arunksingh16 profile image
Arun Kumar Singh

Good catch.. Sorry for typo, corrected now. Thanks a lot @dogers