DEV Community

Cover image for Terraform Associate Certification: State file
Daniel Huerta
Daniel Huerta

Posted on • Edited on

Terraform Associate Certification: State file

If you have started using Terraform as your Infrastructure as Code tool you might wonder how does TF know which resources need to be created, deleted, or modified when you run your code. Well, let me tell you that it is not a magic stuff, the agent behind this is the state file 😉.

Terraform apply

Every time we deploy our Infrastructure with terraform apply, a file named terraform.tfstate is created, it includes all the information about the resources that are currently deployed in the cloud.

You can navigate on it and you will see a key with the name of resources, it is an array which lists all the elements that were created with the configuration file (after doing terraform apply).

If you create an EC2 instance in AWS, your tfstate file will look like this:

carbon (2)

To understand better how this works, it is important to talk about the Current and Desired State

Current State

The terraform.tfstate file is the responsible to store the current state of the infrastructure, it is to say all the information about the resources that are currently deployed in your Cloud Provider (after the terraform apply command has been run).

Desired State

All the code that is set in the main.tf file corresponds to the desired state, on it you specify what resources you expect to be created in the Cloud, and here is where the magic occurs 😉.

Terraform is going to compare both states (current and desired one), if there is an existing difference between both, it will make the changes that are necessary so that the current state is equal to the desired state.
TF shows the result of the comparison when we execute the terraform plan command in the terminal.

Refreshing the state

But, what if we modify a resource directly in the Cloud Provider interface not using Terraform apply (AWS Console for instance), let's say that we changed the EC2 instance type from t2.micro to t2.large, how is our local terraform.tfstate be modified to match with those remote changes? 🤔.

Well, Terraform has the solution for that. We just need to run the command terraform refresh and all the configuration that is currently running in the cloud provider will be updated in the local terraform.tfstate file.

Closure

Now that you understand the state concepts in Terraform, we can start talking about how to manage it in a collaborative workflow, let's talk about the remote state in a different post.

Thanks for reading, any comments or suggestions are welcome. We are here to help each other 😉💙.

Top comments (0)