Home > Software design >  export a environment variable for terraform does not work?
export a environment variable for terraform does not work?

Time:05-21

i am trying to set a environment variable for terraform

using export TF_VAR_instanceType="t2.nano"

my tf file looks something like this:-

resource "aws_instance" "myFirstEc2Instance" {

  ami           = "ami-0ca285d4c2cda3300"
  instance_type = var.instanceType
}

Note there is terraform.tfvars as well as variables.tf files too, i am trying to see how exporting environment variables work in Mac. It is using value present terraform.tfvars file.

CodePudding user response:

It's because terraform uses TF_VAR as a fallback. So if it finds the variable in terraform.tfvars it'll use the value. If not, then we'll search for other instances and use the last one it finds.

As a fallback for the other ways of defining variables, Terraform searches the environment of its own process for environment variables named TF_VAR_ followed by the name of a declared variable.

Source

if the same variable is assigned multiple values, Terraform uses the last value it finds, overriding any previous values. Note that the same variable cannot be assigned multiple values within a single source.

So this looks like:

  • Environment variables
  • The terraform.tfvars file, if present.
  • The terraform.tfvars.json file, if present.
  • Any *.auto.tfvars or *.auto.tfvars.json files, processed in lexical order of their filenames.
  • Any -var and -var-file options on the command line, in the order they are provided. (This includes variables set by a Terraform Cloud workspace.)

Source

  • Related