|
|
Terraform Variables, Locals and Outputs
Author: Venkata Sudhakar
Terraform variables make your configurations reusable and environment-agnostic. Instead of hardcoding values like region, instance size, or project ID directly in resource definitions, you define them as input variables with optional defaults and validation rules. The same Terraform configuration can then be applied to dev, staging, and production environments simply by supplying different variable values, without changing any resource code. Terraform supports three types of values: input variables (var.) which are the inputs to a configuration that callers supply, local values (local.) which are computed intermediate values you define once and reuse throughout the configuration to avoid repetition, and output values which expose attributes of created resources so they can be consumed by other Terraform modules or used in CI/CD pipelines. Together, variables, locals, and outputs make Terraform configurations modular, DRY (Do not Repeat Yourself), and composable. The below example shows a complete variables.tf, locals.tf, and outputs.tf for a multi-environment GCP deployment, demonstrating all variable types including string, number, bool, list, map, and object.
locals.tf and outputs.tf showing computed values and resource outputs,
Using the locals in resource definitions and running apply for different environments,
It gives the following output,
# Dev apply:
local.name_prefix = "my-project-dev"
local.vm_machine_type = "e2-micro"
local.db_disk_size = 10
Apply complete! Resources: 3 added.
Outputs:
vm_name = "my-project-dev-server"
vm_external_ip = "34.72.10.11"
bucket_name = "my-project-dev-data"
# Prod apply:
local.name_prefix = "my-project-prod"
local.vm_machine_type = "n2-standard-4"
local.db_disk_size = 200 (100 * 2 for prod)
Apply complete! Resources: 3 added.
Outputs:
vm_name = "my-project-prod-server"
vm_external_ip = "34.102.200.5"
bucket_name = "my-project-prod-data"
# Validation error when wrong environment is supplied:
Error: Invalid value for variable
environment must be dev, staging or prod.
Variable precedence order (highest to lowest): 1. Command-line -var and -var-file flags. 2. Environment variables prefixed with TF_VAR_ (e.g. TF_VAR_project_id). 3. terraform.tfvars or terraform.tfvars.json in the working directory. 4. *.auto.tfvars files. 5. Default values defined in the variable block. Variables with no default and not supplied through any of these methods will prompt interactively during plan and apply.
|
|