Variable vs Local in Terraform: Key Differences and Usage
variable defines input values that users or modules can set from outside, while local defines internal values computed within the configuration. Variables are for external configuration, and locals are for simplifying expressions inside the code.Quick Comparison
This table summarizes the main differences between variable and local in Terraform.
| Aspect | Variable | Local |
|---|---|---|
| Purpose | Input values set externally | Internal computed values |
| Definition Location | Declared with variable block | Declared with locals block |
| Value Source | Provided by user, environment, or defaults | Derived from expressions in config |
| Changeability | Can be overridden at runtime | Fixed within the configuration |
| Use Case | Configure modules or root module inputs | Simplify complex expressions or reuse values |
| Visibility | Accessible outside the module | Only accessible inside the module |
Key Differences
Variables in Terraform are designed to accept input from users or calling modules. They allow you to customize your infrastructure by passing values when you run Terraform commands or through environment variables. Variables can have default values but are primarily meant for external configuration.
Locals, on the other hand, are used to define values inside your Terraform configuration that are computed from other values. They help you avoid repeating complex expressions and make your code cleaner. Locals cannot be set or overridden from outside; they are fixed once defined.
In summary, use variables to accept input and locals to simplify and reuse computed values within your Terraform code.
Code Comparison
Here is an example showing how to use a variable to accept an input value for an AWS region.
variable "region" { description = "The AWS region to deploy resources" type = string default = "us-west-2" } provider "aws" { region = var.region } resource "aws_s3_bucket" "example" { bucket = "my-bucket-${var.region}" acl = "private" }
Local Equivalent
Here is how to use a local value to compute the bucket name inside the configuration.
locals {
region = "us-west-2"
bucket_name = "my-bucket-${local.region}"
}
provider "aws" {
region = local.region
}
resource "aws_s3_bucket" "example" {
bucket = local.bucket_name
acl = "private"
}When to Use Which
Choose variable when you want to allow users or modules to provide input values that can change between runs or environments. This makes your Terraform code flexible and reusable.
Choose local when you want to simplify your configuration by computing values from other inputs or constants inside your code. Locals help keep your code clean and avoid repetition but are not meant for external input.
Key Takeaways
variable to accept input values from users or modules.local to define internal computed values within your configuration.