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.
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.
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.
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
.
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.