Knowing how to manage Terraform state is key. The TFState
file in Terraform is what makes it very different from other systems. You can spin and launch infrastructures with other configuration management tools like Chef, Saltstack and Ansible, but the biggest difference with Terraform relies on this state.
You can see your TFState file as a big JSON
structure of the reality of your infrastructure working together with the Terraform code in which you declare the so called “desired state” you want to achieve.
This desired state is declarative, which means that when you declare within your code that you want a specific resource with a specific configuration and when you apply
this code, Terraform will “talk” to your Cloud provider’s API, and then spawn all those resources. Once it’s done, it will write the reality of the deployment on the cloud provider’s side on this JSON file.
At the end of the day, you have 3 situations with 3 parties:
- your code
- the reality on your cloud provider’s account
- the state file.
The state file is exactly the mirror of the last successful apply of your code. It works with any kind of resources, which means that you can do this with your cloud provider if you’re interested by launching infrastructure resources, but you can do this as well with any kind of providers.
Let’s say that you deploy helm charts
using Terraform. If you do so, you will have a state file of your deployments as well. It’s the same with github, if you use the github provider. If you define users, and the same user is used for a project on GCP and an IAM
on AWS as a github user, it’s going to be dumped for this specific user, all linked on the Terraform state file.
Consider it as the reference for the reality of the existing infrastructure which you can refer to, from inside your code.
So basically, a state file is the reality of your deployment on your cloud provider from the intention declared on your Terraform code.