Terraform
Define input variables
You now have enough Terraform knowledge to create useful configurations, but the examples so far have used hard-coded values. Terraform configurations can include variables to make your configuration more dynamic and flexible.
Define input variables
Working in your learn-terraform-gcp
directory, create a new file called
variables.tf
with the following variable definitions.
variable "project" { }
variable "region" {
default = "us-central1"
}
variable "zone" {
default = "us-central1-c"
}
Tip
Terraform loads all files ending in .tf
in the working
directory, so you can name your configuration files however you choose. We
recommend defining variables in their own file to make your configuration easier to
organize and understand.
This file defines four variables within your Terraform configuration. The
project
and credentials_file
variables have an empty block: { }
. The
region
and zone
variables set defaults. If a default value is set, the
variable is optional. Otherwise, the variable is required. If you run
terraform plan
now, Terraform will prompt you for the values for project
and credentials_file
.
Use variables in configuration
Next, update the GCP provider configuration in main.tf
to use these new
variables.
terraform {
required_providers {
google = {
source = "hashicorp/google"
version = "6.8.0"
}
}
}
provider "google" {
- project = "<PROJECT_ID>"
- region = "us-central1"
- zone = "us-central1-c"
+ project = var.project
+ region = var.region
+ zone = var.zone
}
Variables are referenced with the var.
prefix.
Assign values to your variables.
You can populate variables using values from a file. Terraform
automatically loads files called terraform.tfvars
or matching *.auto.tfvars
in the working directory when running operations.
Create a file named terraform.tfvars
and copy and paste the values below. Be sure to replace <PROJECT_ID>
and
<FILE>
with your GCP project ID and the path to your key file.
project = "<PROJECT_ID>"
Save this file.
Warning
In other configurations, you may store credentials in the terraform.tfvars
file. Never commit sensitive values into source control.
Apply configuration
Now run terraform apply
.
$ terraform apply
google_compute_network.vpc_network: Refreshing state... [id=projects/testing-project/global/networks/terraform-network]
google_compute_instance.vm_instance: Refreshing state... [id=projects/testing-project/zones/us-central1-c/instances/terraform-instance]
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Since the region and zone input variables are configured with defaults, you do not need to set them. The values you set in your variables file match the original configuration, so Terraform does not need to make any changes to your infrastructure.
Terraform supports many ways to use and set variables. To learn more, follow our in-depth tutorial, Customize Terraform Configuration with Variables.