itye1970
itye1970

Reputation: 1975

Terraform variable files

I am trying to use a variables file to deploy resource groups in Azure using Terraform but it works if I only have one variable. If I use two I get an error:

"invalid value "variables.tf" for flag -var-file: multiple map declarations not supported for variables"

The variables file is as below :

variable "resource_group_name" {
  description = "The name of the resource group in which the resources will be created"
  default     = "im-from-the-variables-file"
}

variable "location" {
  description = "The location/region where the virtual network is created. Changing this forces a new resource to be created."
  default     = "west europe"
}

The main file used to deploy is as below:

resource "azurerm_resource_group" "vm" {
  name     = "${var.resource_group_name}"
  location = "${var.location}"
}

Upvotes: 2

Views: 2343

Answers (2)

slashpai
slashpai

Reputation: 1169

Adding to what ydaetskcoR has mentioned in above answer. If you have already specified default values in variable file for all variables defined and you need just that default values you don't even need to pass -var-file since default values will be used if you don't pass values

Upvotes: 0

ydaetskcoR
ydaetskcoR

Reputation: 56839

You've confused the variable definition syntax to the variable setting syntax.

Terraform will concatenate all the .tf files in a directory so your variables.tf file (assuming it's in the same directory as your main.tf (or whatever contains your azurerm_resource_group resources etc) is already included.

You need to define every variable before it can be used so things like:

resource "azurerm_resource_group" "vm" {
  name     = "${var.resource_group_name}"
  location = "${var.location}"
}

by themselves would not be valid as the variables resource_group_name and location are not defined.

You define variables with the syntax you've used in your variables.tf file:

variable "location" {
  description = "The location/region where the virtual network is created. Changing this forces a new resource to be created."
  default     = "west europe"
}

To override the defaults (if wanted or if a default isn't provided) then you need to either pass the variable in at run time (using TF_VAR_location environment variables or by using -var location="west us") or you can define vars files that take the form:

location = "west us"
resource_group_name = "im-from-the-variables-file"

Terraform will automatically load any files in the directory called terraform.tfvars or *.auto.tfvars and you can also define extra vars files at any point by using -var-file=myvars.tfvars as you have attempted to do (but with a .tf file containing HCL instead of key-pairs.

Upvotes: 6

Related Questions