Day 63 Terraform Variables

Day 63 Terraform Variables

Day 63 of #90daysofdevops

Hey Techies! Welcome to this blog

In this blog, we are going to start with Terraform Variables.

Understanding Terraform Variables

Variables are fundamental constructs in every programming language because they are inherently useful in building dynamic programs. We use variables to store temporary values so that they can assist programming logic in simple as well as complex programs.

In this post, we discuss how variables are used in Terraform. Terraform uses HCL (Hashicorp Configuration Language) to encode infrastructure. It is declarative in nature, meaning several blocks of code are declared to create a desired set of infrastructure.

Before we dive into various types of variables, it is helpful to think of the complete Terraform configuration as a single function. As far as variables are concerned, we use them with function in the form of arguments, return values, and local variables. These are analogous to input variables, output variables, and local variables in Terraform.

Terraform Input Variables

Terraform input variables are used as parameters to input values at run time to customize our deployments. Input terraform variables can be defined in the main.tf configuration file but it is a best practice to define them in a separate variable.tf file to provide better readability and organization.

A variable is defined by using a variable block with a label. The label is the name of the variable and must be unique among all the variables in the same configuration.

variables.tf file

The variable declaration can optionally include three arguments:

  • description: briefly explain the purpose of the variable and what kind of value is expected.

  • type: specifies the type of value such as string, number, bool, map, list, etc.

  • default: If present, the variable is considered to be optional and if no value is set, the default value is used.

Terraform Input Variables Types

The type argument in a variable block allows you to enforce type constraints on the variables a user passes in. Terraform supports a number of types, including string, number, bool, list, map, set, object, tuple, and any.

If a type isn’t specified, then Terraform assumes the type is any. Now, let’s have a look at some of these terraform variables types and their classification.

Primitive Types

A primitive type is a simple type that isn’t made from any other type. The available primitive types are:

  • string: a sequence of characters representing some text, such as “hello”.

  • number: a numeric value. The number type can represent both whole numbers like 15 and fractional values such as 6.28318.

  • bool: either true or false.

    Complex Types

    A complex type is a type that groups multiple values into a single value. These values could be of a similar type or different types.

    • List: A Terraform list variable is a sequence of similar values indexed by numbers (starting with 0). It accepts any type of value as long as they are all of the same types. Lists can be defined either implicitly or explicitly.

list variable define

  • Map: A map is a collection of values where each value is identified by a string label.
    In the example below is a map variable named managed_disk_type to define the type of storage we want to use based on the region in Azure. In the default block, there are two string values, “Premium_LRS” and “Standard_LRS” with a named label to identify each one westus2 and eastus.

    map variable define

  • Object: An object is a structural type that can contain different types of values, unlike map, list. It is a collection of named attributes that each have their own type.
    In the below example, we have declared an object type variable os for the os image that can be used to deploy a VM.

    object variable define

Lists, maps, and objects are the three most common complex variable types. They all can be used for their specific use cases.

Use Input Variables

After declaration, we can use the variables in our main.tf file by calling that variable in the var.<name> format. The value to the variables is assigned during terraform apply.

main.tf file

Assign Values To Input Variables

There are multiple ways to assign values to variables. The following is the descending order of precedence in which variables are considered.

1. Command-line flags

The most simple way to assign value to a variable is using the -var option in the command line when running the terraform plan and terraform apply commands.

$ terraform apply -var="resourceGroupName=terraformdemo-rg" -var="location=eastus"

2. Variable Definition (.tfvars) Files

If there are many variable values to input, we can define them in a variable definition file. Terraform also automatically loads a number of variable definitions files if they are present:

  • Files named exactly terraform.tfvars or terraform.tfvars.json

  • Any files with names ending in .auto.tfvars or .auto.tfvars.json

terraform.tfvars file

If the file is named something else, then use the -var-file flag directly to specify a file.

$ terraform apply -var-file="testing.tfvars"

3. Terraform Environment Variables

Terraform searches the environment of its own process for environment variables named TF_VAR_<var-name> followed by the name of a declared variable. Terraform scans all variables starting with TF_VAR and uses those as variable values for Terraform.

$ export TF_VAR_location=eastus

This can be useful when running Terraform in automation, or when running a sequence of Terraform commands in succession with the same terraform variables.

Define Output Variables

Outputs allow us to define values in the configuration that we want to share with other resources or modules. For example, we could pass on the output information for the public IP address of a server to another process.

An output variable is defined by using an output block with a label. The label must be unique as it can be used to reference the output’s value. Let’s define an output to show us the public IP address of the server. Add this to any of the *.tf files.
Multiple output blocks can be defined to specify multiple output variables. Outputs are only shown when Terraform applies your plan, running a Terraform plan will not render any outputs.

Uses of Terraform Variables

Now that we’ve covered the types let’s explore how these variables are used in practice.

Configuration Reusability

Terraform variables enable you to reuse configurations across different environments or projects. By changing input variables, you can deploy the same infrastructure with slight variations, making your code highly adaptable.

Dynamic Resource Creation

Input variables allow you to dynamically create resources based on user input. For instance, you can use variables to specify the number of virtual machines or the size of a database server during deployment.

Collaboration and Sharing

Output variables enable you to share critical information with other configurations. This promotes collaboration between different Terraform projects and simplifies the integration of your infrastructure with external systems.

Enhanced Maintainability

Local variables help in maintaining clean and organized configuration files. They prevent a repetition of code and make it easier to update values consistently across your project.

Map: Mapping Values

Maps in Terraform are collections of key-value pairs, making them useful for variables with distinct names and associated values. In our exploration, we'll begin by focusing on the Map data type.

variable "file_contents" {
    type = map
    default = {
        "statement1" = "this is a file"
        "statement2" = "this is my file"
    }
}

Task-01: Creating a Local File

Let's put our knowledge into practice by creating a local file using Terraform. We'll utilize the Map variable to dynamically set the content of the file.

resource "local_file" "myfile" {
    filename = var.filename
    content = var.file_contents["statement1"]

}

variable "filename" {
    type = string
    default = "output.txt"
}

Now, the local file resource is configured with content from the Map variable.

Task-02: List, Set, and Object Datatypes

Terraform supports various data types beyond Map. Let's explore List, Set, and Object in Terraform variables.

List: Ordered Collections

variable "colors" {
  type    = list(string)
  default = ["red", "green", "blue"]
}

Set: Unordered Collections

variable "unique_numbers" {
  type    = set(number)
  default = [1, 2, 3, 4, 5]
}

Object: Complex Structures

variable "user" {
  type = object({
    name  = string
    age   = number
    email = string
  })

  default = {
    name  = "John Doe"
    age   = 30
    email = "john.doe@example.com"
  }
}

Experiment with these variable types to enhance the flexibility and scalability of your Terraform code.

Thank you so much for taking the time to read till the end! Hope you found this blog informative and helpful.

Feel free to explore more of my content, and don't hesitate to reach out if need any assistance from me or in case of you have any questions.

Happy Learning!

~kritika :)

Connect with me: LinkedIn