description to explain the variable’s intended purpose. Additionally, you can enforce data types using the type argument. The optional sensitive argument (defaulting to false) hides variable values during operations like terraform plan or terraform apply when set to true.
Below is an example of two variable blocks that include these common arguments:
Even if a variable is marked as sensitive, its value will still be stored in the Terraform state file.
Adding Validation to Variables
Terraform allows you to define validation rules within a variable block. For example, consider an AMI variable that should always start with “ami-”. You can enforce this requirement using a validation block, where thesubstring function extracts the first four characters and verifies they match “ami-”. If the condition is not met, Terraform displays the provided error message.
-var flag, you’ll see an error similar to the following:
Simple Variable Types
Terraform supports several simple variable types, includingstring, number, and boolean. Here’s how you can define variables of these types:
1 to a boolean), an error will be raised.
Below is an example demonstrating type conversion:
Working with Lists
A list is an ordered collection of values. In the example below, the variableservers is defined as a list containing three elements. The first element has an index of 0, the second an index of 1, and so on:
Using Maps
Maps store data as key-value pairs, providing a way to associate specific values with named keys. The following example defines a map variable for instance types, which differentiates between production and development environments:Understanding Sets
Sets are similar to lists in that they are collections of values, but they do not allow duplicate elements. If duplicate values are provided, Terraform will signal an error during operations. Examples of valid and invalid set declarations:Complex Data Structures
Terraform supports complex data structures, such as objects and tuples, to manage hierarchical and heterogeneous data.Object Type
An object allows you to combine different types within a single variable. Consider the example of a variable representing details of a cat named Bella:Tuple
Unlike lists, tuples can contain elements of different types. The types of each element in a tuple are explicitly defined within square brackets. The following example illustrates a tuple variable:That concludes our overview of using variables in Terraform. Mastery of these variable types and validation rules can significantly enhance the flexibility and reliability of your Terraform configurations. Future articles will delve deeper into advanced Terraform configurations and best practices. For additional reading, check out these Terraform documentation resources.