In Terraform, variables are essential for creating flexible and reusable configurations. They allow you to manage dynamic values efficiently, making your infrastructure code more adaptable. Here's a breakdown of how Terraform variables work:
Types of Variables
- Input Variables: These are defined in
.tffiles and enable you to provide dynamic values to your configuration. - Environment Variables: You can set values directly in your environment using the
TF_VAR_prefix (e.g.,TF_VAR_variable_name=value). - Output Variables: These are defined in output blocks, allowing you to pass values from one module to another or to display results after applying the configuration.
Declaring Variables
Variables in Terraform are declared using the variable block within .tf files. Here's an example:
variable "instance_type" {
type = string
description = "The type of instance to launch"
default = "t2.micro"
}
Types of Variable Values
- String: Used for text values.
- Number: For numerical values.
- Bool: For boolean values (true or false).
- Complex Types: These include lists, maps, and objects, which allow for structured data.
Assigning Values
You can assign values to variables in different ways:
- Default Values: Directly set within the variable block.
- Command-Line Flags: Use the
-varflag when running commands (e.g.,terraform apply -var="instance_type=t2.large"). - Files: Specify values in
.tfvarsfiles and load them using the-var-fileoption.
Variable Precedence
Terraform follows this order of precedence when determining which variable value to use:
- Command-line flags
.tfvarsfiles- Environment variables
- Default values
Sensitive Variables
If you're working with sensitive data (like passwords), you can mask them in the output logs by setting sensitive = true in the variable definition. This ensures sensitive values are not exposed.
By leveraging variables in Terraform, you can easily adjust your infrastructure configuration without needing to modify the core code. This makes your code more modular and adaptable to different environments or scenarios.

Comments
Post a Comment