How to Create And use Variables File With Terraform

In this blog post, I will show you how to create and use a variables file with Terraform and create a more dynamic configuration.

In the previous articles about Terraform, we used variables in the main configuration file and applied the configuration; however, there is a better way to use Terraform variables.

A variable helps us keep the configuration dynamic and clean simultaneously by separating the variables from the main configuration.


In the following example, I will create a resource group in Microsoft Azure using a file and a configuration file called terraform.tfvars.

Let’s start with

Configuration file (

The following configuration will create a resource group in Azure. If you look closely, you will see that I’m using two variables for the name and location of the RG.

terraform {
   required_providers {
     azurerm = {
       source = "hashicorp/azurerm"
       version = ">= 2.41"
 provider "azurerm" {
   features {}
 variable "rgname" {
     default = "Myrgname" 
 variable "rglocation" {
     default = "westus"
 resource "azurerm_resource_group" "rg" {
   name     = var.rgname
   location = var.rglocation

To use a variables file, I will create a new file in the same folder as my folder and will call it terraform.tfvars.

Variables file (terraform.tfvars)

The following configuration of the variable file is straightforward as you can see below. The file only contains the values for variables. Terraform is smart enough to know what to do with the values and populate the configuration.

rgname = "rg0001"
rglocation = "eastus"

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.