Terraform Variables Usage

LinuxBeginner
Practice Now

Introduction

Terraform is a powerful tool for building, changing, and versioning infrastructure safely and efficiently. A key feature that makes Terraform configurations flexible and reusable is the use of input variables. Variables allow you to parameterize your configurations, so you can avoid hardcoding values and easily customize deployments without changing the source code.

In this lab, you will learn the fundamentals of using Terraform variables. You will create a simple configuration that generates a local file. The name and content of this file will be determined by variables that you define and pass during the execution of your Terraform commands.

By the end of this lab, you will understand:

  • How to declare variables in a .tf file.
  • How to reference variables within a resource block.
  • How to supply values for your variables when running terraform apply.

Create variables.tf file for variable definitions

In this step, you will create a dedicated file to hold your variable declarations. While you can declare variables in any .tf file, it is a common convention to place them in a file named variables.tf. This practice helps keep your project organized and makes it easy for others to understand what input values your configuration expects.

All your work will be done in the ~/project directory. First, create the variables.tf file using the touch command.

touch variables.tf

You can verify that the file has been created by listing the contents of the directory:

ls

You should see variables.tf in the output.

variables.tf

For now, this file is empty. In the following steps, you will add variable definitions to it.

Define string variable for filename

In this step, you will define your first variable. This variable will be used to specify the name of the file that Terraform will create.

Variables are declared using a variable block. Each block defines a single input variable. Let's define a variable named filename.

Open the variables.tf file you created in the previous step using the nano editor.

nano variables.tf

Now, add the following code to the file. This code declares a variable named filename, specifies its type as string, and includes a helpful description.

variable "filename" {
  description = "The name of the file to create."
  type        = string
}
  • variable "filename": This starts the declaration of a variable named filename.
  • description: This optional argument provides a human-readable description of the variable's purpose.
  • type: This argument specifies the data type for the variable. Here, we use string to indicate it will accept text values.

After adding the code, save the file and exit nano by pressing Ctrl+X, followed by Y, and then Enter.

Define string variable for content

In this step, you will define a second variable to hold the content that will be written into the file. This follows the same pattern as the previous step.

Open the variables.tf file again with nano.

nano variables.tf

Add the following variable block below the filename variable definition you added earlier.

variable "content" {
  description = "The content to write into the file."
  type        = string
}

Your complete variables.tf file should now look like this:

variable "filename" {
  description = "The name of the file to create."
  type        = string
}

variable "content" {
  description = "The content to write into the file."
  type        = string
}

This defines two input parameters for your Terraform configuration: one for the filename and one for its content.

Save the file and exit nano (Ctrl+X, Y, Enter).

Reference variables in local_file resource block

In this step, you will create the main Terraform configuration file, main.tf, and use the variables you just defined. You will use the local_file resource, which is part of the hashicorp/local provider, to create a file on the local filesystem.

First, create a new file named main.tf.

nano main.tf

Now, add the following configuration to the main.tf file.

terraform {
  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "2.4.0"
    }
  }
}

resource "local_file" "my_file" {
  filename = var.filename
  content  = var.content
}

Let's break down this configuration:

  • terraform { ... }: This block configures Terraform settings, including the required providers. We are telling Terraform that our configuration needs the local provider.
  • resource "local_file" "my_file": This defines a resource of type local_file and gives it a local name my_file.
  • filename = var.filename: This is where you reference a variable. The var. prefix followed by the variable name (filename) tells Terraform to use the value of the filename variable for this argument.
  • content = var.content: Similarly, this assigns the value of the content variable to the content argument of the resource.

After adding the code, save the file and exit nano (Ctrl+X, Y, Enter).

Run terraform apply with variable values

In this final step, you will execute your Terraform configuration and provide values for your variables.

First, you need to initialize the Terraform working directory. The terraform init command downloads and installs the providers defined in the configuration (in our case, the local provider).

Run the following command:

terraform init

You should see output indicating that Terraform has been successfully initialized.

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/local versions matching "2.4.0"...
- Installing hashicorp/local v2.4.0...
- Installed hashicorp/local v2.4.0 (signed by HashiCorp)

Terraform has been successfully initialized!
...

Now, you can apply the configuration. To pass values to your variables, you can use the -var command-line flag. We will also use the -auto-approve flag to skip the interactive confirmation prompt.

Run the terraform apply command with values for filename and content:

terraform apply -var="filename=hello.txt" -var="content=Hello, Terraform Variables." -auto-approve

Terraform will now execute the plan and create the file. The output will look similar to this:

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  ## local_file.my_file will be created
  + resource "local_file" "my_file" {
      + content              = "Hello, Terraform Variables."
      + directory_permission = "0777"
      + file_permission      = "0777"
      + filename             = "hello.txt"
      + id                   = "..."
    }

Plan: 1 to add, 0 to change, 0 to destroy.

local_file.my_file: Creating...
local_file.my_file: Creation complete after 0s [id=...]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

To verify that everything worked, use the cat command to display the contents of the newly created file.

cat hello.txt

You should see the content you provided in the variable:

Hello, Terraform Variables.

Congratulations! You have successfully used Terraform variables to create a file.

Summary

In this lab, you have learned the fundamental workflow for using variables in Terraform. You successfully parameterized a configuration, making it more dynamic and reusable.

You have learned how to:

  • Organize variable declarations in a dedicated variables.tf file.
  • Declare variables using the variable block, specifying their type and description.
  • Reference variables within resource blocks using the var.<variable_name> syntax.
  • Initialize a Terraform project with terraform init to download necessary providers.
  • Supply variable values at runtime using the -var flag with the terraform apply command.

This knowledge is a crucial building block for creating more complex and modular infrastructure as code with Terraform.