DEV Community

BIRhrt
BIRhrt

Posted on

Terraform, but Safer — How I Built tf-safe to Protect State Files Automatically

Terraform gives us infrastructure as code — but managing its state securely is a hidden risk.
Your .tfstate file often includes:

Secrets in plaintext

Cloud resource details

Sensitive metadata

If that file’s lost or leaked, your infra is exposed.

So I built tf-safe
— a lightweight CLI that wraps Terraform to handle backups, encryption, and recovery automatically.

⚙️ The Problem

I once ran terraform apply on a shared workspace and accidentally overwrote the remote state.
No backup. No recovery. Hours of pain.

Terraform has backends, but no built-in safety net.
I wanted a “Terraform but safer” workflow.

💡 The Solution: tf-safe

tf-safe acts as a wrapper around Terraform:

  1. Hooks into each command (plan, apply, destroy)
  2. Backs up your state file
  3. Encrypts it (AES-256 or AWS KMS)
  4. Uploads it to local or S3 backend
  5. Retains old versions for recovery

🔧 Setup

brew tap BIRhrt/tap
brew install BIRhrt/tap/tf-safe

tf-safe init
tf-safe apply

📁 Example .tf-safe.yaml

backend: s3
s3:
bucket: tf-safe-backups
region: ap-south-1
encryption: kms
kms_key_id: arn:aws:kms:ap-south-1:123456789012:key/abc123
retention_days: 30

🧠 How It Works Under the Hood

tf-safe wraps Terraform CLI commands.
Before each command, it copies the current .tfstate → backup location.
After command success, it re-encrypts and versions it.
Failures trigger a fallback restore.

🧩 Roadmap

  • Azure Blob & GCS backend
  • Terraform Cloud integration
  • GitHub Actions plugin
  • Custom retention policies

🔗 Links

GitHub → https://github.com/BIRhrt/tf-safe

If you use Terraform daily, give it a try and drop your feedback 🙏

Top comments (0)