How to Run Terraform with Input Variables
Table of Contents
- Introduction
- Sample Terraform Code
- Run the Sample Terraform
- Use Variables
- Different Values for Each Environment
- Conclusion
Introduction
This blog shows how to use Terraform variables to move environment-specific values out of the code, so you can run the same Terraform configuration for different environments and inject the appropriate variables for each one.
Sample Terraform Code
This blog uses the following Terraform code to get started.
provider.tf
terraform {
required_providers {
google = {
source = "hashicorp/google"
version = "5.15.0"
}
}
}
provider "google" {
# Configuration options
credentials = file("your google credential file path")
project = "{gcp project id}"
}
backend.tf
terraform {
backend "gcs" {
bucket = "{gcp bucket for terraform}"
prefix = "test"
}
}
schedule-job.tf
resource "google_bigquery_data_transfer_config" "job" {
display_name = "my_test_sj"
project = "{your project id}"
location = "us"
data_source_id = "scheduled_query"
schedule = "first sunday of quarter 00:00"
params = {
query = "call spTest();"
}
}
Run the Sample Terraform
Running the above sample Terraform should create a scheduled job.
Use Variables
Now, let's say we want to move the display_name to a variable, because we want to reuse the same name later.
Let's create a new variable.tf. If you run terraform plan, you can see the display name as my_test_sj.
Variable with Default
variable "bq_name" {
type = string
nullable = false
default = "my_test_sj"
}
Without Default Variable
Let's say we want to enter the name every time we run Terraform. We can remove the default so that every time we run terraform plan, it will ask for input for the variable. The example here might not be ideal, but there may be some areas where this approach is useful.
variable "bq_name" {
type = string
nullable = false
}
Different Values for Each Environment
Assume we have 2 different workspaces: dev and qa.
For this case, we define the variables as below.
variable.tf
variable "bq_name" {
type = string
nullable = false
}
dev.tfvars
Create a dev.tfvars file and add the following key-value pairs.
name = "dev_job"
qa.tfvars
Create a qa.tfvars file and add the following key-value pairs.
name = "qa_job"
At this point, nothing needs to be modified in the schedule job Terraform file. We'll run terraform plan with the option --var-file=dev.tfvars. This will run Terraform with the key/value environment variables defined in dev.tfvars.
terraform plan --var-file=dev.tfvars
Conclusion
Using Terraform workspaces with var-file allows you to write Terraform configurations for different environments, keeping environment-specific values separate from your infrastructure code.