ChrisAdkin
ChrisAdkin

Reputation: 1326

terraform module structure and tfvars files

I have a configuration which uses modules, this is its structure:

main.tf
       \modules
               \kubernetes_cluster
                                  \main.tf
                                  \variables.tf

At this stage I had no separate tfvars file, I relied on default values declared in the variables.tf file, and this worked fine. I then decided to create a tfvars file resulting in:

main.tf
       \modules
               \kubernetes_cluster
                                  \main.tf
                                  \variables.tf
                                  \variables.tfvars

At the same time I removed the default values from variables file, then when I ran:

terraform apply -target=module.kubernetes_cluster -auto-approve

I got errors complaining that I needed to pass my variables in as arguments due to the fact "They were missing", so I moved to this:

main.tf
variables.tf
variables.tfvars
                \modules
                \kubernetes_cluster
                                   \main.tf
                                   \variables.tf

this is what main.tf in the root module looks like:

module "kubernetes_cluster" {
  source  = "./modules/kubernetes_cluster"
  kubernetes_version  = var.kubernetes_version
  node_hosts          = var.node_hosts
}

When I run terraform apply I get prompted for the values of the variables. All I want to do is not rely on variable default values and to be able to run terraform apply from the root module directory without having to pass in variable values by hand, I suspect that my module structure somewhere along the line is not correct.

Upvotes: 0

Views: 3047

Answers (2)

Nullish Byte
Nullish Byte

Reputation: 396

As per the documentation, terraform automatically loads tfvars if:

  • Either variable file name is terraform.var or terraform.var.json
  • Or YOUR_NAME.auto.tfvar

So in your case renaming variables.tfvars to variables.auto.tfvars would work

Upvotes: 0

Marcin
Marcin

Reputation: 238727

If you want to have TF load tfvars automatically, the file must be called terraform.tfvars, not variables.tfvars. There are other possibilities:

Terraform also automatically loads a number of variable definitions files if they are present:

Files named exactly terraform.tfvars or terraform.tfvars.json.

Any files with names ending in .auto.tfvars or .auto.tfvars.json.

Upvotes: 1

Related Questions