Dit deel is nog niet vertaald. Je ziet de Engelse tekst.
$ als gewone gebruiker# als root (of met sudo)
Vaardigheden in dit hoofdstuk
- Lokale en externe state, locking en drift
Know the local backend
Without a backend block, state is saved in terraform.tfstate in the working folder (the local backend).
- Good for learning and one-person tests.
- Bad for teams: no sharing, no locking, easy to lose or to commit by mistake.
Use a remote backend
The backend block in the terraform block saves state remotely. On Azure: a storage account container.
terraform {
backend "azurerm" {
resource_group_name = "rg-tfstate"
storage_account_name = "sttfstate2026"
container_name = "tfstate"
key = "shop/prod.tfstate"
use_azuread_auth = true
}
}az storage account create -g rg-tfstate -n sttfstate2026 --sku Standard_ZRS --min-tls-version TLS1_2 --allow-blob-public-access false
az storage container create --account-name sttfstate2026 -n tfstate --auth-mode login
terraform init -migrate-state| Backend | Locking |
|---|---|
azurerm (Azure Storage) | Blob lease |
s3 (AWS) | S3 lock file (use_lockfile) or DynamoDB |
gcs (Google) | Built in |
HCP Terraform (cloud block) | Built in, plus runs and history |
Onthoud
The backend block can not use variables. Use -backend-config=FILE for values that differ per environment (partial configuration).
Know state locking
While a plan or apply runs, the backend locks the state, so two runs can not change it at the same time.
Find and fix drift
Drift = someone changed a resource outside Terraform (portal, CLI). The next plan shows it.
| Situation | What to do |
|---|---|
| The manual change was wrong | terraform apply puts the code's values back |
| The manual change is right | Change the code to match, then plan shows no changes |
| Only update the state with real values | terraform apply -refresh-only |
| A resource was deleted by hand | Plan shows it will be created again |
terraform plan -refresh-only
terraform apply -refresh-only
terraform plan -detailed-exitcode ; echo $?-detailed-exitcode returns 2 when there are changes — a nightly drift check in CI can alert on that.
Read the state safely
Never edit the state file by hand. Use the state commands.
terraform state list
terraform state show azurerm_virtual_network.app
terraform state pull > backup.tfstateMore state commands (move, remove, import) are in Maintain infrastructure.