Referencing Variables, Modules, and State File

Learn how to read variables and understand the purpose of the module directory and state file.

We'll cover the following

Referencing variables

So far, you’ve learned a lot about how to define variables but ultimately you need to read them too. Reading variables is the easy part! Once you’ve defined a variable and have assigned it a value, you can reference that variable’s value by using an expression.

Perhaps you’ve created the variable called virtualMachineName and need to reference that variable’s value inside of a configuration file. To do that, you can use an expression. You can see an example of the syntax to do this below.

resource azurerm_virtual_machine "VM" {
    name = var.virtualMachineName
}

Modules

So far, you’ve learned about various configuration files like the main configuration file main.tf, an optional variable configuration, and a variable definition file (TFVARS). These three files are stored in a single directory. The directory is typically named after what the configuration as a whole is creating. For example, if the configuration creates an AzureVM, the directory might be called AzureVM. The directory (AzureVM) where the Terraform configuration files are stored is called a module.

State file

When you run the Terraform binary, Terraform reads all configuration files inside of the current directory to figure out what to build. It evaluates all of the variables and other logic you created inside of those configuration files to create a state. That state then represents the values of all configuration items Terraform needs to manage infrastructure defined in the configuration files or the module.

A state file consists of all metadata for the resources that Terraform is managing. The state file contains components like the subscription ID, virtual machine name, resource group that the resources will reside in, and many others.

Think of a Terraform state file like a bucket of products to create chocolate chip cookies. You have chocolate chips, flour, and mixing supplies, etc. Without all of those products, you can’t make chocolate chip cookies and without a Terraform state file, you can’t create or manage Azure resources.

When you run Terraform, Terraform creates a state file to store the current state of the resources under management called terraform.tfstate. A state file holds what type of resource is being created and the provider that’s being used with name, location, and so on. The state file holds everything Terraform needs to create or update those resources.

Get hands-on with 1200+ tech skills courses.