How to run Terraform with Input Variable
Sample Terraform Code
This blog is using below 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
Run the above sample terraform should create a schedule job.
Use Variable
Now, let's say we want to move the display_name to the variable, because we want to re-use the same name later.
Let's create a new *variable.tf, and 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"
}
with out default variable
let's say we want to enter the name every time when we run the terraform, we can remove the default so every time run the terraform plan if will ask the input for the variable. The example here might not be idea, but there might be some area can be use this.
variable "bq_name" {
type = string
nullable = false
}
different value for each environments
Assume we have 2 different workspace 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 and add the below key values.
name = "dev_job"
qa.tfvars
create a qa.tfvars and add the below key values.
name = "qa_job"
So far at this point, nothing need to modify at the schedule job terraform file, but we'll run the terraform plan with this option --var-file=dev.tfvars, this will run the terraform with the key/value environments files defined at dev.tfvars.
terraform plan --var-file=dev.tfvars
Conclusion
Use the terraform workspace with var-file can write the terraform for different environments.