Terraform to read variables from environment

Viewed 6412

I have written a terraform configuration with variable definition like:

variable "GOOGLE_CLOUD_REGION" {
  type = string
}

When I run terraform plan I am asked to fill in this variable even though this variable is set within my environment.

Is there a way to tell terraform to work with current env vars? Or do I have to export them and pass them somehow manually one-by-one?

3 Answers

You can define the environment variable TF_VAR_GOOGLE_CLOUD_REGION to set that variable.

If you are using bash, it might look like this:

export TF_VAR_GOOGLE_CLOUD_REGION="$GOOGLE_CLOUD_REGION"
terraform apply ...

From Environment Variables under Configuration Language: Input Variables.

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.

This can be useful when running Terraform in automation, or when running a sequence of Terraform commands in succession with the same variables. For example, at a bash prompt on a Unix system:

$ export TF_VAR_image_id=ami-abc123 $ terraform plan ...

You can create a file that ends with .tfvars or .tfvars.json and then when you run a plan you specify that file:

terraform apply -var-file="example.tfvars"

If you name the file terraform.tfvars or terraform.tfvars.json or have a file with names ending in .auto.tfvars or .auto.tfvars.json then Terraform automatically loads the variable definition file and you don't have to manually specify it when you run a plan.

An example of what the terraform.tfvars file will look like:

first_env_var = "environment_variable_one"
second_env_var = "environment_variable_two"

An example of what the terraform.tfvars.json file will look like:

{
  "image_id": "ami-abc123",
  "availability_zone_names": ["us-west-1a", "us-west-1c"]
}

I would approach this by creating a variables.tf file, within the project directory. with the required variable block you can specify a default:

variable "GOOGLE_CLOUD_REGION" {
type = string
default = "us-west1"
}

this will then be used as the default value during each run, and you will not be prompted.

Related