Know about Terraform State Files , Current State and Desired State

  • Terrafrom stores the state about your managed infrastructure and configuration .
  • State/state files created from the TF files.
  • This state is used by Terraform to map real world resources to your configuration, keep track of metadata.
  • This state is stored by default in a local file named “terraform.tfstate”, but it can also be stored remotely, which works better in a team environment.
  • Terraform uses this local state to create plans and make changes to your infrastructure.
  • Prior to any operation, Terraform does a refresh to update the state with the real infrastructure.
  • Terrafrom state makes bindings between objects in a remote system and resource instances declared in your configuration.
  • Manually editing this file is not recommended , use state commands for basic modification
  • If any difference found in remote environment , based on state configuration it will update the remote environment objects , like modify , delete, create etc. Along with the state file also update about new identity of objects.
  • It’s JSON file , you can find in your working dir, or your remote directory.

Here you can see all the information about github repository which is created by terraform earlier.

Now lets try to update tf files to craete ec2 instance and see changes in state file,

resource "aws_instance" "yourec2" {
ami = "ami-0eeb03e72075b9bcc"
instance_type = "t2.micro"

Now new EC2 instance created . We can able to see state file gets updated.

Now lets do one more test , we can change the instance type from t2.micro to t2.nano and lets execute “terraform apply”

Now manually changed the instance type to t2.nano

Now if we run “terraform apply” it asks to change the instance type as per tf config files and state files.

When you execute “terraform refresh” it will update state file by comparing with real world resource .

For an example lets change change the aws ec2 instance type manually to t2.small

Now execute “terraform refresh” , it will update the state file .

The stat file get updated to t2.small.

If you execute “terrafrom plan” again it will read from config tf files, and update the state file. If we confirm it will change in the target infrastructure.

In summary

tf config files==>tf state file===>Target Environment.


Leave a Reply