Sobes.tech
Junior

What is a tfstate file in Terraform?

sobes.tech AI

Answer from AI

The tfstate file stores the current state of the infrastructure managed by Terraform. It is a key element that allows Terraform to track real resources and their compliance with the configuration in HCL.

The file records:

  • The identifier, type, and attributes of each resource.
  • Information about relationships between resources.
  • Data about the provider and module versions.

When executing Terraform commands, it accesses the tfstate:

  • terraform plan: Compares the current state with the desired state (described in configuration files) and determines future actions (create, modify, delete).
  • terraform apply: Applies the changes described in the plan and updates the tfstate as resources are created or modified.
  • terraform destroy: Uses information from tfstate to delete all managed resources.

Importance of tfstate:

  • It is the single source of truth about the infrastructure state.
  • It helps avoid manual synchronization of state with cloud providers.
  • It is critical for collaborative work on a project, as it coordinates changes.

Recommendations for working with tfstate:

  • Use a remote backend (e.g., S3, Google Cloud Storage, Azure Storage) for storing tfstate. This provides centralized storage, state locking (protection against concurrent changes), and versioning.
  • Never store tfstate in version control systems (Git), as it may contain sensitive information and grow rapidly.

Example of storing in a remote S3 backend:

terraform {
  backend "s3" {
    bucket = "my-terraform-state-bucket" # S3 bucket name
    key    = "path/to/my/terraform.tfstate" # Path to the state file in the bucket
    region = "us-east-1" # AWS region
    # profile = "my-aws-profile" # Optional: AWS profile
    # encrypt = true # Optional: server-side encryption
    # dynamodb_table = "my-terraform-state-lock" # Optional: DynamoDB table for locking
  }
}