How the Terraform state file is created
Overview
- In the IT field, infrastructure as a code helps maintain an application’s underlying infrastructure by using programming.
- Terraform is a coding tool aligned with this practice which allows us to define cloud and local resources in formatted configuration files that we can reuse and share.
- When we build infrastructure in Terraform configuration, a state file gets created in the local workspace directory named
terraform.tfstate.
The state file
- The state file is a JSON containing the definition of our infrastructure. The file works with the Terraform code to define the “desired state” that we’ll like to achieve.
- Whenever we change the configuration file, it automatically determines which part of our configuration is already created and which needs to be changed with the help of this file.
- The state file helps provide a reference to Terraform to identify if a resource is present and stop it from being created again.
- The following code executes the Terraform infrastructure for a simple
hello state .tffile and displays the state file.
resource "local_file" "hello_state_file" {
content = "Hello terraform state!"
filename = "${path.module}/hello_state.txt"
}Terraform module with terraform state file
Explanation
In the above code, we initialize a Terraform module using terraform init, and then create a Terraform state file using terraform apply -auto-approve.
We see that terraform.tfstate file is created using ls.
We can also see the content of terraform.tfstate file using cat terraform.tfstate.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved