Terraform is a stateful
application. This means that it keeps track of everything it builds in your cloud environments so that if you need to change something or delete something later, Terraform will know what it built, and it can go back and make those changes for you.
That state is stored in what a
state file
.
Terraform records information about what infrastructure it created in a Terraform state file. By default, when you run Terraform in the folder /foo/bar
, it will create the file /foo/bar/terraform.tfstate
.
This file contains a custom JSON format that records a mapping from the Terraform resources in your templates to the representation of those resources in the real world.
For example, let’s say your Terraform template contained the following:
resource "aws_instance" "example" {ami = "ami-0c55b159cbfafe1f0"instance_type = "t2.micro"}
After running terraform apply
, the terraform.tfstate
file will look something like this:
{"version": 4,"terraform_version": "0.12.0","serial": 1,"lineage": "1f2087f9-4b3c-1b66-65db-8b78faafc6fb","outputs": {},"resources": [{"mode": "managed","type": "aws_instance","name": "example","provider": "provider.aws","instances": [{"schema_version": 1,"attributes": {"ami": "ami-0c55b159cbfafe1f0","availability_zone": "us-east-2c","id": "i-00d689a0acc43af0f","instance_state": "running","instance_type": "t2.micro","(...)": "(truncated)"}}]}]}
Idempotence | Whenever a Terraform configuration is applied, Terraform checks if there is an actual change made. Only the resources that are changed will be updated. |
Deducing dependencies | Terraform maintains a list of dependencies in the state file so that it can properly deal with dependencies that no longer exist in the current configuration. |
Performance | Terraform can be told to skip the refresh even when a configuration change is made. Only a particular resource can be refreshed without triggering a full refresh of the state, hence imporving performance. |
Collaboration | State keeps track of the version of an applied configuration, and it's stored in a remote, shared location. So collaboration is easily done without overwriting. |
Auditing | Invalid access can be identified by enabling logging. |
Safer storage | Storing state on the remote server helps prevent sensitive information. |
Free Resources