DEV Community

Sainath Patil
Sainath Patil

Posted on

State File Management & Remote Backend with S3

Most critical concepts in Terraform: State Management.
Terraform uses a state file to track the real-world infrastructure it manages. Understanding and securing this file is essential for any production-ready setup.

How Terraform Updates Infrastructure
Terraform follows a simple rule:

Keep the actual state equal to the desired state.

It compares:

  • Actual state stored in terraform.tfstate

  • Desired state defined in configuration files

Then it updates only the resources that need changes nothing more, nothing less.

What’s Inside the Terraform State File?

The state file is a JSON file containing:

  • Resource metadata

  • Dependencies

  • Attribute values

  • Provider info

  • Current configuration snapshot

Remote Backend with AWS S3
A remote backend stores your state in the cloud instead of your local machine.

Benefits

  • Team collaboration

  • Built-in reliability and durability

  • Automatic locking

  • Encryption and access control

  • Versioning for rollback

Components

  • S3 Bucket = Stores the state

  • IAM Policies = Control access

S3 Native State Locking (Terraform 1.10+)

Terraform 1.10 introduced S3 native locking, eliminating the need for DynamoDB tables.

How it Works

  • Terraform tries to create a .tflock file in S3

  • S3 uses conditional writes

  • If file exists = lock failed

  • If not = lock created

  • After apply = lock file removed (delete marker)

DynamoDB locking is now discouraged and may be deprecated soon.

Testing State Locking

  • Run terraform apply in Terminal 1
  • Run terraform plan in Terminal 2 You should see:
Error acquiring the state lock
StatusCode: 412
Enter fullscreen mode Exit fullscreen mode

This confirms that native S3 locking is working correctly.

Conclusion
Understanding of how Terraform tracks infrastructure and why remote backends are essential for any real-world deployment. With S3 native locking now available, state management is simpler, safer, and more enterprise-friendly than ever.

video: https://youtu.be/YsEdrl9O5os?si=jyNfhqFe9UlEOeEl

Top comments (0)