How to Use String Variables in Terraform: Simple Guide
In Terraform, you declare a string variable using the
variable block with type = string. You assign a value to it in a terraform.tfvars file or via command line, then reference it in your configuration using var.variable_name.Syntax
To use a string variable in Terraform, you first declare it with a variable block specifying the type as string. Then you assign a value either in a .tfvars file or directly in the command line. Finally, you reference the variable in your Terraform configuration using var.variable_name.
- variable block: declares the variable and its type.
- default: optional default value if none is provided.
- var.variable_name: how to use the variable in resources.
terraform
variable "example_string" { type = string default = "Hello, Terraform!" } # Usage in resource output "greeting" { value = var.example_string }
Example
This example shows how to declare a string variable, assign a value in a terraform.tfvars file, and output the value. It demonstrates how Terraform reads and uses string variables in configuration.
terraform
variable "region" { type = string } output "selected_region" { value = var.region } # terraform.tfvars file content: # region = "us-west-2"
Output
selected_region = "us-west-2"
Common Pitfalls
Common mistakes include forgetting to assign a value to a variable without a default, which causes errors, or using incorrect syntax when referencing variables. Also, mixing quotes or not using var. prefix leads to issues.
terraform
/* Wrong: missing var prefix */ output "wrong_usage" { value = example_string } /* Right: correct variable reference */ output "correct_usage" { value = var.example_string }
Quick Reference
| Concept | Syntax | Description |
|---|---|---|
| Declare string variable | variable "name" { type = string } | Defines a string variable |
| Assign value | name = "value" (in .tfvars) | Sets variable value externally |
| Use variable | var.name | References variable in config |
| Default value | default = "value" | Optional fallback value |
Key Takeaways
Declare string variables with a variable block and type string.
Assign values in terraform.tfvars or via command line to avoid errors.
Reference variables using var.variable_name syntax in your config.
Always provide a default or assign a value to prevent missing variable errors.
Use consistent quotes and the var prefix to avoid syntax mistakes.