Terraform 24: Local vs remote state for team collaboration
easy⏱ 5 mincourseterraform
Local state: one file, one machine
With no backend configured, Terraform writes terraform.tfstate in your working directory. It works, but the file lives only on your disk. A teammate running apply from their clone has a stale or empty state, so Terraform thinks nothing exists and tries to recreate everything — or two people apply at once and clobber each other's changes.
# Implicit default — no backend block = local state on disk
# ./terraform.tfstate (current state)
# ./terraform.tfstate.backup (previous state)
#
# Great for a throwaway demo. Never for a shared environment.
Remote state: one shared, locked copy
A remote backend stores the single canonical state in the cloud (e.g. an Azure Storage container). Everyone's init points at the same object, so every plan/apply reads the same reality. Remote backends also give you locking (one apply at a time) and encryption at rest — you get the collaboration guarantees local state can't provide.
Migrating existing state
If you already applied with local state and then add a backend block, terraform init detects the change and offers to copy your existing state up to the remote. Answer yes (or pass -migrate-state) so history is preserved — you do not start from scratch.
Pick the backend
Implement pickBackend(teamSize) so it returns "remote" when more than one person shares the config (teamSize > 1) and "local" otherwise. The starter logs pickBackend(1) and pickBackend(4).