Sobes.tech
Junior — Middle

How can accidental deletion of the state file in Terraform be prevented?

sobes.tech AI

Answer from AI

To prevent accidental deletion of the state file in Terraform, several approaches can be used:

  • State Locking: When using a remote backend (e.g., S3 with DynamoDB, Terraform Cloud), state locking is enabled, which prevents concurrent modifications and accidental deletions.

  • Backup: Regularly save backups of the state file so it can be restored if deleted.

  • Access Restrictions: Configure permissions for the state file and storage so that only authorized users can modify or delete it.

  • Using -lock and -lock-timeout options: When executing Terraform commands, explicitly enable locking to avoid conflicts.

  • Implementing review and control processes: For example, using CI/CD where state changes are reviewed.

Example of configuring a remote backend with locking in S3:

terraform {
  backend "s3" {
    bucket         = "my-terraform-state"
    key            = "path/to/my/key"
    region         = "us-east-1"
    dynamodb_table = "terraform-lock"
    encrypt        = true
  }
}