In this lesson, we take an in-depth look at the Terraform variable block, exploring how to define variables, enforce type constraints, and work with complex data structures. Learn how to leverage Terraform’s variable capabilities to write more efficient and maintainable infrastructure code.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Basic Variable Definition
Terraform variable blocks can include several parameters, including a default value that sets a fallback for the variable. Below is an example that defines several variables with default values:type and description. The description provides clarity on the variable’s purpose, while the type enforces the kind of data the variable can hold. For example:
Simple Variable Types
Terraform supports several simple variable types. Here’s a quick overview:- String: Accepts alphanumeric values.
- Number: Accepts numeric values (both positive and negative).
- Boolean: Accepts values of either
trueorfalse.
List Variables
A list is an ordered collection of values where each element can be accessed by its index (starting at 0). For example, consider a variable that uses a list of prefixes:var.prefix[0]returns “Mr”var.prefix[1]returns “Mrs”var.prefix[2]returns “Sir”
Map Variables
Maps allow you to define key-value pairs for storing related data. For example, the following variable stores file content:List and Map Type Constraints
You can enforce type constraints on lists and maps to ensure all elements are of a specific type. For example:If the default values do not match the declared type, Terraform will produce an error when running
terraform plan or terraform apply. For instance, using a string when a number is required will trigger an error.Set Variables
Sets in Terraform are similar to lists but automatically remove duplicate elements. Consider these examples of valid set declarations:Object Variables
Objects allow you to create complex structures by combining various data types. For example, you can define an object representing a cat with multiple attributes:Tuple Variables
Tuples in Terraform are like lists but allow elements of different types. The order and type of the elements are strictly defined. For example, consider this tuple variable:Running
terraform plan with the above configuration will generate an error indicating that the default value does not match the tuple’s required type structure.That’s the end of this lesson. In the next section, we will explore how to work with variable types in Terraform in greater detail. For additional resources, refer to the Terraform Documentation and other related materials.