What is variable.tf and terraform.tfvars?
Terraform variable.tf is a file where you can define variables for your Terraform configuration. This file can contain the variable definitions as well as the optional default value for the variable. Here is an example of variable.tf
which has -
-
Two variables with no default value -
instance_type
,github_repo
-
One variable with default value -
location
1# variable.tf 2 3 # No default value 4 variable "instance_type" { 5 type = string 6 description = "EC2 Instance Type" 7 } 8 9 # No default value 10 variable "tag" { 11 type = string 12 description = "The tag for the EC2 instance" 13 } 14 15 # default value for the variable location 16 variable "location" { 17 type = string 18 description = "The project region" 19 default = "eu-central1" 20 }
Terraform.tfvars is a file where you actually assign a values to the variables. I am just gonna use the previous variable.tf
and assign the values to the variables -
1 # terraform-dev.tfvars
2
3 instance_type = "t2.micro"
4 tag = "EC2 Instnace for DEV"
5 location = "eu-central-1"
Here are the benefits of using terraform.tfvars
-
- You can have multiple
terraform.tfvars
based on your project setup for example -- DEV -
terraform-dev.tfvars
- QA -
terraform-qa.tfvars
- PROD -
terraform-prod.tfvars
- DEV -
Table of Content
- How to create variable.tf?
- How to create terraform.tfvars?
- How to create multiple .tfvars files for different environments?
- How do you pass a variable(.tfvars) to the command line to Terraform using --var-file?
- Best practices for using variable.tf and terraform.tfvars
- Difference between terraform.tfvars vs variables.tf
- Terraform variable loading preference - How do terraform loads variables?
- How to pass variables into a module in Terraform?
- Conclusion
Pre-requisite
Before we start working with Terraform variables, here are the pre-requisites -
- You must install terraform (click here on how to install terraform)
- You must have either AWS or Google Cloud account (Click to here for AWS and Google Cloud terraform setup tutorial)
1. How to create variable.tf?
Let's take a very basic example to understand the concept of variable.tf
in terraform. In this example, we are going to set up an EC2 Instance on AWS..
For setting up an EC2 Instance we will need the following information -
- Region -
location
- Instance Type -
instance_type
- Tags -
tag
1.1 Let's create variable.tf file for region, instance type, and tags -
Here is the code for variable.tf
-
1# variable.tf
2
3# No default value
4variable "instance_type" {
5 type = string
6 description = "EC2 Instance Type"
7}
8
9# No default value
10variable "tag" {
11 type = string
12 description = "The tag for the EC2 instance"
13}
14
15# default value for the variable location
16variable "location" {
17 type = string
18 description = "The project region"
19 default = "eu-central1"
20}
1.2 Create main.tf for provisioning EC2 instance -
Here is the code for main.tf
file
1provider "aws" {
2 region = var.location
3 access_key = "<INSERT_YOU_ACCESS_KEY>"
4 secret_key = "<INSERT_YOU_SECRET_KEY>"
5}
6
7resource "aws_instance" "ec2_example" {
8
9 ami = "ami-0767046d1677be5a0"
10 instance_type = var.instance_type
11
12 tags = {
13 Name = var.tag
14 }
15}
2. How to create terraform.tfvars?
After creating the variables.tf
in Step-1, let's create .tfvars
and in that file, we are going to assign values to the variable -
location
- "eu-central-1"instance_type
- "t2.micro"tag
- "EC2 Instnace for DEV"
1# terraform.tfvars
2
3instance_type = "t2.micro"
4tag = "EC2 Instnace for DEV"
5location = "eu-central-1"
3. How to create multiple .tfvars files for different environments?
There can be a situation where you need to create multiple tfvars files based on the environment like DEV, QA, PRODUCTION
.
So in such scenario, you can create one tfvars
file for each environment -
- terraform-dev.tfvars
- terraform-qa.tfvars
- terraform-prod.tfvars
Here is the content of terraform-dev.tfvars, terraform-qa.tfvars, terraform-prod.tfvars
based on different environment types -
DEV
1# terraform-dev.tfvars
2
3instance_type = "t2.micro"
4tag = "EC2 Instnace for DEV"
5location = "eu-central-1"
QA
1# terraform-qa.tfvars
2
3instance_type = "t2.micro"
4tag = "EC2 Instnace for QA"
5location = "eu-central-1"
PROD
1# terraform-prod.tfvars
2
3instance_type = "t2.micro"
4tag = "EC2 Instnace for PROD"
5location = "eu-central-1"
4. How do you pass a variable(.tfvars) to the command line to Terraform using --var-file?
Referencing the same example from Step-2 we can pass the variables terraform-dev.tfvars, terraform-qa.tfvars, terraform-prod.tfvars
based on the environment we are working.
Here is how I am going to run the terraform init, terraform plan and terraform apply
command in DEV, QA, and PROD environment.
DEV - Keep in mind that you have to supply the correct .tfvars
file based on the environment you are working on.
1# 1. terraform init for DEV
2
3terraform init --var-file="terraform-dev.tfvars"
4
5# 2. terraform plan for DEV
6
7terraform plan --var-file="terraform-dev.tfvars"
8
9# 3. terraform apply for DEV
10
11terraform apply --var-file="terraform-dev.tfvars"
QA - Keep in mind that you have to supply the correct .tfvars
file based on the environment you are working on.
1# 1. terraform init for QA
2
3terraform init --var-file="terraform-qa.tfvars"
4
5# 2. terraform plan for QA
6
7terraform plan --var-file="terraform-qa.tfvars"
8
9# 3. terraform apply for QA
10
11terraform apply --var-file="terraform-qa.tfvars"
PROD - Keep in mind that you have to supply the correct .tfvars
file based on the environment you are working on.
1# 1. terraform init for PROD
2
3terraform init --var-file="terraform-prod.tfvars"
4
5# 2. terraform plan for PROD
6
7terraform plan --var-file="terraform-prod.tfvars"
8
9# 3. terraform apply for PROD
10
11terraform apply --var-file="terraform-prod.tfvars"
5. Best practices for using variable.tf and terraform.tfvars
- Separate reusable variables into a separate tfvars file: Having a separate
.tfvars
file for all reusable variables provides clarity, readability, and maintainability. Below you will find a screenshot of my project where i have 3 differenttfvars
forDEV, QA, PROD
environment -
-
Lockdown read/write access: Ensure that only the appropriate people can modify the variable values, whether through IAM policies or other security controls.
-
Use default values: Whenever possible, set default values for variables that can be overridden later. This simplifies the process of managing variable values and reduces risk. Here is an example of how to set default values -
1# default value assigned for variable `location` 2 3variable "location" { 4 type = string 5 description = "The project region" 6 default = "eu-central1" 7}
-
Reuse variable names: Reusing variable names between variable.tf and terraform.tfvars helps reduce confusion and ensures that all variable values referenced in variable.tf can be overridden in terraform.tfvars.
-
Organize variable values: Organize, group, and document the variables to provide context and clarity. This will reduce the amount of time needed to understand what values are being used for
6. Difference between terraform.tfvars vs variables.tf
Here are my 5 key differences between terraform.tfvars
and variables.tf
-
Terraform.tfvars | variables.tf |
---|---|
It stores variable values | It stores variable definitions such as data type and possible values |
Terraform.tfvars are local configuration files | variables.tf files are used to define variables in multiple environments |
Terraform.tfvars is sourced automatically by Terraform at runtime | variables.tf must be specified explicitly when running Terraform commands |
Variables in Terraform.tfvars are only valid for that particular environment | variables in variables.tf can be used across environments when defined properly |
Terraform.tfvars provides default values for the variables declared in variables.tf | variables.tf do not provide any default values |
7. Terraform variable loading preference - How do terraform loads variables?
Terraform variable loading preference refers to the order in which Terraform on loads variables when multiple sources specify the same variable. By default, Terraform looks in the following order to find variables with the same name.
- Environment variables
- Variable files (files with a
.tfvars
orterraform.tfvars.json
extension) - From Terraform files (using
.tf
files) - From the command line (using the
-var
flag)
Once all relevant sources are checked, the first encountered value for a given variable is used. Variables can be made available by setting them in the environment, or in a variable file. If a variable is set in multiple sources, the ordering described above is followed.
8. How to pass variables into a module in Terraform?
There are three ways to define the variables for module -
- Define variables inside the module's
main.tf
: The first and the easiest way to define the variables inside themain.tf
of terraform module. Here is the screenshot of my project in which I have createdmain.tf
and in the same file I have declared the variables -
- Create
variables.tf
for each module: The most recommended way of passing variables to the module is by creating individualvariables.tf
for each module so that your terraform code is more optimized.
Please have a look at the screenshot of my project structure. In this screenshot, you will find two modules -
- module-1 : There is
variables.tf
for module-1 - module-2 : As well as there is separate
variables.tf
for module-2
- Common project level
variables.tf
for all modules: The third option would be to create commonvariables.tf
at the project level so that all the modules within that project can access the samevariables.tf
.
Here is the screenshot of the project in which I have created common variables.tf
for all the modules -
- Pass variables to modules from the command line: Just like we pass
variable
from the command line in terraform similarly you can also the variables from the command line to all the modules within that project.
But the variables passed via the command line will override all the local variables.
Here are some example commands for passing the variables to modules -
1terraform init --var-file="terraform.tfvars"
2
3terraform plan--var-file="terraform.tfvars"
4
5terraform apply--var-file="terraform.tfvars"
9. Conclusion
I hope this article will help you to understand the variables.tf
and terraform.tfvars
in more detailed way. You can clone my GitHub Repo for Terraform where I have created all the sample codes.
Read More - Terragrunt -
Posts in this Series
- Use Terraform to manage AWS IAM Policies, Roles and Users
- How to split Your Terraform main.tf File into Multiple Files
- How to use Terraform variable within variable
- Mastering the Terraform Lookup Function for Dynamic Keys
- Copy files to EC2 and S3 bucket using Terraform
- Troubleshooting Error creating EC2 Subnet InvalidSubnet Range The CIDR is Invalid
- Troubleshooting InvalidParameter Security group and subnet belong to different networks
- Managing strings in Terraform: A comprehensive guide
- How to use terraform depends_on meta argument?
- What is user_data in Terraform?
- Why you should not store terraform state file(.tfstate) inside Git Repository?
- How to import existing resource using terraform import comand?
- Terraform - A detailed guide on setting up ALB(Application Load Balancer) and SSL?
- Testing Infrastructure as Code with Terraform?
- How to remove a resource from Terraform state?
- What is Terraform null Resource?
- In terraform how to skip creation of resource if the resource already exist?
- How to setup Virtual machine on Google Cloud Platform
- How to use Terraform locals?
- Terraform Guide - Docker Containers & AWS ECR(elastic container registry)?
- How to generate SSH key in Terraform using tls_private_key?
- How to fix-Terraform Error acquiring the state lock ConditionalCheckFiledException?
- Terraform Template - A complete guide?
- How to use Terragrunt?
- Terraform and AWS Multi account Setup?
- Terraform and AWS credentials handling?
- How to fix-error configuring S3 Backend no valid credential sources for S3 Backend found?
- Terraform state locking using DynamoDB (aws_dynamodb_table)?
- Managing Terraform states?
- Securing AWS secrets using HashiCorp Vault with Terraform?
- How to use Workspaces in Terraform?
- How to run specific terraform resource, module, target?
- How Terraform modules works?
- Secure AWS EC2s & GCP VMs with Terraform SSH Keys!
- What is terraform provisioner?
- Is terraform destroy needed before terraform apply?
- How to fix terraform error Your query returned no results. Please change your search criteria and try again?
- How to use Terraform Data sources?
- How to use Terraform resource meta arguments?
- How to use Terraform Dynamic blocks?
- Terraform - How to nuke AWS resources and save additional AWS infrastructure cost?
- Understanding terraform count, for_each and for loop?
- How to use Terraform output values?
- How to fix error configuring Terraform AWS Provider error validating provider credentials error calling sts GetCallerIdentity SignatureDoesNotMatch?
- How to fix Invalid function argument on line in provider credentials file google Invalid value for path parameter no file exists
- How to fix error value for undeclared variable a variable named was assigned on the command line?
- What is variable.tf and terraform.tfvars?
- How to use Terraform Variables - Locals,Input,Output
- Terraform create EC2 Instance on AWS
- How to fix Error creating service account googleapi Error 403 Identity and Access Management (IAM) API has not been used in project before or it is disabled
- Install terraform on Ubuntu 20.04, CentOS 8, MacOS, Windows 10, Fedora 33, Red hat 8 and Solaris 11