Search code examples
terraformdatasourceterraform-provider-gcp

Load config from external file to the terraform


I use Terraform to provide some Google infrastructure. I would like to store some configuration variables in an external (non-terraform) config file. The idea is to use those variables in the Terraform and bash also, so I wouldn't like to use typical .tfvars file. How to achieve this?

I have got three files and let's assume for simplicity, that they are being stored in the same directory.

General configuration files with the variables to ingest:

# config.txt
GOOGLE_PROJECT_ID='my-test-name'
GOOGLE_REGION='my-region'

Terraform file with the datasources:

# datasources.tf
data "local_file" "local_config_file" {
  filename = "./config.txt"
}

Terraform file with the variables:

# variables.tf
variable "project_id" {}

variable "region" {
  default = 'europe-west3'
}

Solution

  • If all of your variables you'd like to use in Terraform are string-type variables, you can define them as environment variables to use them in Terraform and your Bash scripts:

    Terraform will read environment variables in the form of TF_VAR_name to find the value for a variable. For example, the TF_VAR_region variable can be set in the shell to set the region variable in Terraform.

    # config.sh
    export TF_VAR_region="my-region"
    export TF_VAR_project_id="my-test-name"
    

    Note that this approach won't work for list or map type variables:

    Note: Environment variables can only populate string-type variables. List and map type variables must be populated via one of the other mechanisms.

    See the docs here for more information.