azureterraform

terraform plan -var-file= is not setting varibles


I have terraform project with two terraform.tfvars files. Inside terraform.tfvars there are e.g:

location                 = "northeurope"
resource_group_name      = "michal_resource_group"

I run terraform init and get message: Terraform has been successfully initialized! so then I run:

terraform plan -var-file=C:\Users\Dev\repo\terraform-dep\terraform\TEST\terraform.tfvars

and it also finishes without any errors:

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

but at this point I think that my variables from terraform.tfvars are not used because when I try terraform apply it says:

var.location
    Location to create the Azure resources.
    Enter a value:

when I type manually norteurope it asks about var.resource_group_name.

I also tried to use:

terraform console
> var.location
(known after apply)

so it doesn't help at all.

What is the problem here? I am sure at terraform plan stage it looks at my 'terraform.tfvars' file because if I put there wrong values it fails.


Solution

  • If the terraform.tfvars file is in a different directory, make sure to create main.tf and variables.tf in the same directory.

    If you are still facing an error, rename terraform.tfvars to terraform.auto.tfvars.

    I tested this in my environment by creating main.tf, variables.tf, and terraform.tfvars in another directory and passed the full path in terraform plan and terraform apply as shown below

    main.tf

    provider "azurerm" {
      features {}
      subscription_id = "837-d7e60e5f09a9"
    }
    
    resource "azurerm_resource_group" "rg" {
      name     = var.resource_group_name
      location = var.location
    }
    
    

    variables.tf

    variable "location" {
      description = "Azure region where the resource group will be created"
      type        = string
    }
    
    variable "resource_group_name" {
      description = "The name of the Azure Resource Group"
      type        = string
    }
    

    terraform.tfvars in another directory

    location =  "northeurope"
    resource_group_name =  "devops-rg"
    

    enter image description here

    enter image description here