Aléas numériques

Linux, infosec and whatever crosses my mind.


» Terraform Cloud & .tfvars

Tl;Dr: rename the terraform.tfvars file into terraform.auto.tfvars when using Terraform Cloud.

I had an interesting issue today while trying to deploy Terraform manifests. For simple projects which are handled by only few engineers, we use Terraform Cloud. It quite easy to use, handles pretty nicely the tfstate and has a good GitHub integration (here Terraform Cloud performing a terraform plan on a pull request):

Terraform Cloud perfoming a plan on a pull request

I created a variables.tf file, containing the following:

variable "cloudflare_zone_id" {
  type        = string
  description = "Cloudflare zone ID"
  validation {
    condition     = can(regex("^[a-f0-9]{32}$", var.cloudflare_zone_id))
    error_message = "The cloudflare_zone_id value must be a 32-byte string of hex characters."
  }
}

I also created a terraform.tfvars containing the value:

cloudflare_zone_id = "d45cf0895b0a1e665de63100efd643b3"

(No worries, this is not the real ID but the output of curl endless.horse | md5sum :) ).

However, when using terraform plan, I received the following error:

Initializing Terraform configuration...
│ Error: No value for required variable
│   on variables.tf line 1:
│    1: variable "cloudflare_zone_id" {
│ The root module input variable "cloudflare_zone_id" is not set, and has no
│ default value. Use a -var or -var-file command line argument to provide a
│ value for this variable.

Hum, this was intriguing. I started investigating and I first thought that this was due to cloudflare_zone_id having no default value, but when replacing the value with a random 32-byte hex string, it proposed me to destroy all the infrastructure managed by the manifests. So I guess it was not the problem.

After using both terraform fmt and terraform validate and seeing that everything was fine, I resigned and asked to [insert your favorite search engine].

I ended up finding this post on the HashiCorp Discuss entitled “Values from .tfvars not getting loaded”, which was kind of my case.

The first answer states:

When you use Terraform Cloud, the per-workspace Variables stored as part of the workspace settings replace the functionality of the terraform.tfvars file.

Which basically mean that I have to replace the terraform.tfstate file by declaring the variables in Terraform Cloud. However, as the zone ID is not a “sensitive” information (not as sensitive as an API key), we want it to store in code. So the only alternative according to the the doc is to use a file which name is ending by “.auto.tfvars”.

So, a quick mv terraform.tfvars terraform.auto.tfvars did the job:

Plan: 0 to add, 5 to change, 0 to destroy.