Covers recovering a deleted Azure SQL database, diagnosing why Terraform planned a destroy (missing moved blocks, ForceNew attributes, drift), importing restored resources into state, and preventing recurrence with plan gates, prevent_destroy, resource locks, deployment stacks deny settings and scheduled drift detection.
First stop the bleeding: pause the pipeline, put the app into maintenance, and restore. While the logical server still exists, Azure SQL keeps backups of a deleted database, so I restore it to the point just before the delete (az sql db list-deleted, then restore --deleted-time), swap it in for the empty one, and terraform import it so state matches.
Then root cause: the plan showed the database as must be replaced, usually because a refactor changed the resource address without a moved block, or a ForceNew attribute changed, sometimes triggered by portal drift.
Prevention: apply only a reviewed saved plan, fail the pipeline when it contains deletes, add prevent_destroy and CanNotDelete locks on stateful resources, and run scheduled drift detection. The trade-off is a little friction on rare legitimate deletes.
"I treat it as an incident before an engineering puzzle. First I stop any further applies, disable the pipeline's prod stage, and put the API into maintenance mode so nothing writes to the new empty database. Then recovery: Azure SQL keeps automated backups for a dropped database as long as the logical server still exists, so
az sql db list-deletedshows it with its deletion time, and I restore it to a new name at the latest point before the delete. I then rename the empty database out of the way and rename the restored one into place, or point the app's connection at the restored name. Because the database now exists outside Terraform's knowledge, I bring it back under management with animportblock orterraform import, and run a plan until it shows no changes. The data written between the delete and the maintenance switch has to be reconciled separately.For example, at [company] [describe the incident if you have one]: the plan said
-/+ azurerm_mssql_database.orders must be replaced, buried in [about 40] lines of tag changes, and the pipeline used-auto-approve. The cause is usually one of three things. A refactor moved the resource into a module and nobody added amovedblock, so Terraform saw one address destroyed and a new one created. Or a ForceNew attribute changed, such as the collation or a create-mode setting. Or someone changed something in the portal, the state was refreshed, and the configuration change to correct it required replacement. I confirm it with the plan artefact, the state history in the versioned backend, and the Azure Activity Log.Prevention is layered. The pipeline saves the plan, publishes it, and
applyuses exactly that file. A policy step parsesterraform show -jsonand fails if any delete or replace is present unless a named approver overrides. Stateful resources getlifecycle { prevent_destroy = true }and aCanNotDeleteresource lock, which stops a delete even if the tool tries. A nightlyplan -refresh-onlyreports drift, and humans only have Reader in prod. In Bicep the same ideas are what-if, deployment stacks with deny settings, and never using complete mode. The mistake I see is fixing the template but leaving auto-approve on."
| Cause | Plan shows | Fix |
|---|---|---|
| Resource address changed (module refactor, rename) | - destroy old address, + create new |
moved { from = ... to = ... } block |
| ForceNew attribute changed | -/+ must be replaced with # forces replacement |
Revert, or plan a migration (new resource, copy data, cut over) |
| Portal drift on an immutable setting | Replace after refresh | Align code with reality first, then change deliberately |
| Resource removed from code | - destroy |
removed block with lifecycle { destroy = false } to forget without deleting |
| Bicep complete mode | What-if Delete entries |
Use incremental mode or deployment stacks |
| Control | Stops | Does not stop |
|---|---|---|
| Saved plan + human review | Surprises (if people read it) | Reviewers skimming long diffs |
| Automated delete gate on plan JSON | Any delete reaching apply unnoticed | Data corruption from updates |
prevent_destroy |
Terraform planning a destroy | Deletes from portal or other tools |
CanNotDelete lock |
Any delete via ARM, including Terraform and portal | Destructive updates, data deletion inside the DB |
| Soft delete, PITR and LTR backups | Permanent data loss | Downtime |
In a typical case like this, the restore of a [50 GB] General Purpose database takes [30–60 minutes], data written in the [10] minutes before maintenance mode has to be replayed from the outbox or logs, and after adding the delete gate and locks, the next refactor that would have replaced a resource is blocked at plan time.
Checks incident handling under data loss, a real understanding of how Terraform plans destroys, and layered prevention rather than 'be more careful'.
Green flags
Red flags
configuration (.tf) ──┐
├─► plan: for each resource address
state (last known) ───┤ in config, not in state → create
│ in state, not in config → destroy
refresh (live Azure) ─┘ in both, attrs differ → update in place
attr is ForceNew → destroy then create (-/+)
Terraform identifies resources by address (azurerm_mssql_database.orders, module.data.azurerm_mssql_database.orders), not by Azure resource ID. Move a resource into a module and the address changes, so without a moved block it plans a destroy and a create.
ForceNew: some attributes cannot be updated by the Azure API (names, collation, some SKU families, create mode). The provider marks them ForceNew and the plan says # forces replacement.
Drift: during refresh, live values replace stored ones. If the portal change touched an attribute your config sets differently and that attribute is ForceNew, the 'correction' is a replacement.
az sql db list-deleted, az sql db restore --deleted-time). If the server itself was deleted, recovery needs a support case or long-term retention backups, so protect servers with locks.ALTER DATABASE ... MODIFY NAME or az sql db rename) and reconnect.import block (Terraform 1.5+) or terraform import, followed by a clean plan.must be replaced, forces replacement, will be destroyed.moved blocks.terraform plan -out=tfplan ─► terraform show -json tfplan ─► count actions containing "delete"
│ │
└── publish human-readable plan to PR / run summary ├─ 0 → normal approval
└─ >0 → fail, or require named approver
terraform apply tfplan (exactly what was reviewed; no -auto-approve on a fresh plan)
Policy tools (OPA/Conftest, Sentinel in HCP Terraform, or a short script) enforce it.
prevent_destroy makes plan fail for that resource. It does not protect against the resource being removed from config together with the block, so pair it with a lock.CanNotDelete) are enforced by ARM for every client. The pipeline identity should not have rights to remove locks (Microsoft.Authorization/locks/delete is in Owner and User Access Administrator, not Contributor).denySettings (denyDelete) and actionOnUnmanage set to detach for stateful resources; what-if (now also for stacks) as a gate.terraform plan -refresh-only -detailed-exitcode (exit code 2 means changes) or az deployment group what-if, alerting on any difference.azurerm_mssql_database, move it into a module without a moved block, and read the plan. Then add the block and plan again.# forces replacement in the plan.az sql db list-deleted, and restore it with --deleted-time.import block for the restored database and get the plan to 'No changes'.CanNotDelete lock and try terraform destroy; read the error.terraform show -json contains any delete action.Recovery commands, the Terraform changes, and a pipeline gate that blocks destructive plans.
# 1. Find and restore the dropped database (server still exists)
az sql db list-deleted -g rg-orders-prod -s sql-orders-prod -o table
az sql db restore -g rg-orders-prod -s sql-orders-prod \
-n orders --dest-name orders-restored \
--deleted-time "2026-11-18T03:12:45Z" \
--time "2026-11-18T03:12:00Z" # just before the delete
# 2. Swap names: move the empty recreated database aside, put the restored one in place
az sql db rename -g rg-orders-prod -s sql-orders-prod -n orders --new-name orders-empty-incident
az sql db rename -g rg-orders-prod -s sql-orders-prod -n orders-restored --new-name orders
# 3. The refactor moved the database into a module: tell Terraform it is the same resource
moved {
from = azurerm_mssql_database.orders
to = module.data.azurerm_mssql_database.orders
}
# 4. Bring the restored database back under management (Terraform 1.5+)
import {
to = module.data.azurerm_mssql_database.orders
id = "/subscriptions/<sub-id>/resourceGroups/rg-orders-prod/providers/Microsoft.Sql/servers/sql-orders-prod/databases/orders"
}
# modules/data/main.tf
resource "azurerm_mssql_database" "orders" {
name = "orders"
server_id = var.sql_server_id
sku_name = "GP_S_Gen5_2"
long_term_retention_policy {
weekly_retention = "P8W"
}
lifecycle {
prevent_destroy = true # plan fails instead of destroying
}
}
# A delete lock enforced by ARM for every client, Terraform included
resource "azurerm_management_lock" "sql_server" {
name = "do-not-delete"
scope = var.sql_server_id
lock_level = "CanNotDelete"
notes = "Production data. Remove only through a reviewed change."
}
# 5. GitHub Actions: plan, block deletes, apply exactly the reviewed plan
- name: Plan
run: terraform plan -input=false -out=tfplan
- name: Block destructive changes
run: |
deletes=$(terraform show -json tfplan \
| jq '[.resource_changes[] | select(.change.actions | index("delete"))] | length')
echo "Planned deletes or replacements: $deletes"
if [ "$deletes" -gt 0 ]; then
terraform show -json tfplan | jq -r '.resource_changes[] | select(.change.actions | index("delete")) | .address'
echo "::error::Plan deletes resources. Needs the destructive-change approval path."
exit 1
fi
- uses: actions/upload-artifact@v4
with: { name: tfplan, path: tfplan }
# Separate job, 'production' environment with required reviewers
- name: Apply reviewed plan
run: terraform apply -input=false tfplan # no fresh plan, no -auto-approve on new changes
# 6. Nightly drift check: exit code 2 means reality differs from code
terraform plan -refresh-only -detailed-exitcode -input=false || \
{ [ $? -eq 2 ] && echo "Drift detected" && exit 1; }
terraform apply again to 'fix' it. Why it is wrong: The configuration still describes the empty recreated database; a fresh apply can destroy the restored one. Instead: Fix config (moved, import) and confirm the plan shows no changes before any apply.moved blocks. Why it is wrong: Terraform tracks addresses, so it plans destroy and create. Instead: Add moved blocks (Terraform 1.1+; before that, terraform state mv), and check the plan shows moves only.-auto-approve on a plan generated in the same step. Why it is wrong: Nobody sees what will be destroyed. Instead: Save the plan, review it, apply the saved file in a gated job.prevent_destroy alone. Why it is wrong: Deleting the resource block also deletes the protection, and it does nothing against portal or CLI deletes. Instead: Add a CanNotDelete lock the pipeline cannot remove.ignore_changes = all to silence drift. Why it is wrong: It hides real configuration changes, including security settings, so code stops describing reality. Instead: Ignore only specific attributes owned by another process (for example tags set by policy), and fix the rest in code.terraform destroy, and run a timed restore drill each quarter.The senior framing is that IaC makes destruction as easy as creation, so the pipeline must treat deletes as a different class of change. Reviewers do not reliably spot one -/+ in a long plan; machines do. Put the check in code (parse the plan JSON), add a platform-level backstop (locks, deny settings) that the pipeline identity cannot override, and make sure backups and soft delete cover the case where both fail.
On drift, the cure is organisational as much as technical: if people need the portal to fix incidents, give them a fast-tracked PR path and just-in-time access, and run drift detection so a manual change is visible the next morning, not at the next deploy.
| Control | When it fits | Cost | When not to rely on it alone |
|---|---|---|---|
| Automated delete gate | Every prod pipeline | Occasional override for real deletes | Destructive in-place updates |
CanNotDelete locks |
Databases, storage, Key Vault, servers | Deletes need a lock-removal step | Data deleted inside the resource |
| Deployment stacks deny settings | Bicep estates | Learning stacks, exclusions for automation | Non-Azure resources |
| Scheduled drift detection | All environments | Alert noise if code is messy | As a substitute for read-only access |
Measure: number of plans blocked by the delete gate, drift findings per week, restore time in quarterly drills, and recovery point achieved versus target.
First I mitigate, then diagnose. Alerts on 5xx and latency, annotated with the release, tell us the deployment is the likely cause. Then the key decision: roll back if the previous version still works with the current database and messages; roll forward only if rollback is unsafe (a contract change already happened) or the fix is tiny and certain. A feature flag kill switch beats both if the change was flagged.
For migrations that already ran, I don't run down migrations on live data; additive changes stay, and if something destructive ran I restore compatibility (a view or computed column) or use point-in-time restore for the affected data.
Afterwards: a blameless review and pipeline changes such as smoke tests, staged rollout, migration checks and automated rollback. The trade-off is speed of recovery versus certainty about cause.
I treat it like an incident. In Cost Management → Cost analysis I group by service, then resource, then meter, with daily granularity, to find what grew and the day it started. Then I correlate that date with the release history and the Activity Log to find the deployment or config change behind it. Common culprits are Log Analytics ingestion from debug logging, a SKU scaled up and never scaled down, autoscale with no sensible maximum, forgotten test resources, and recursive triggers.
I stop the bleeding first (daily cap, scale down, disable the loop), then fix the root cause, then add guardrails: budgets with action groups, cost anomaly alerts, required tags, Azure Policy for allowed SKUs, and OpenTelemetry sampling. The trade-off is that guardrails like hard caps can drop data or block scaling, so they must be set deliberately, not as a reflex.
I create a user-assigned managed identity first, then a Key Vault with enableRbacAuthorization: true, an Azure SQL server with Entra-only authentication (no SQL admin password), and a Container App that runs as that identity. Access is granted with Microsoft.Authorization/roleAssignments resources whose names are guid(scope, principalId, roleId), so redeployments are idempotent. The app receives AZURE_CLIENT_ID and a password-less connection string, and DefaultAzureCredential does the rest.
.bicepparam files.az deployment group what-if.The trade-off: Bicep handles the Azure control plane well, but it cannot create the SQL database user (a data-plane action), so a pipeline step runs CREATE USER ... FROM EXTERNAL PROVIDER.
How to tell it (STAR)
**S:** At [company], a Terraform refactor moved our production Azure SQL database into a module, and the pipeline applied a plan that destroyed and recreated it empty. **T:** As [on-call / the engineer leading the response] I had to restore service and data, then make sure it could not happen again. **A:** I stopped the pipeline, switched the API to maintenance, restored the dropped database to just before the delete, swapped it in by renaming, and replayed [N] orders from the outbox. I traced the cause to a missing `moved` block, fixed state with `moved` and `import` until the plan was clean, then added a delete gate on the plan JSON, `prevent_destroy`, resource locks and nightly drift detection. **R:** We were back in [about 70] minutes with [no] lost orders, and since then the gate has blocked [N] plans that would have replaced a stateful resource.
Last updated 23 Nov 2026.