📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

A pipeline ran `terraform apply` on production after a refactor, and the Azure SQL database was destroyed and recreated empty. Someone had also changed settings in the portal the week before. How do you recover the data, find out why the plan deleted it, and stop drift and destructive changes reaching production again? Mention plans, Bicep what-if, resource locks and state.

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.

Senior Debugging Advanced azure-sql devops drift incident-response infrastructure-as-code terraform

🎯 Key points

  • Mitigate first: stop pipelines, put the app in maintenance, restore before diagnosing
  • Deleted Azure SQL databases can be restored from automated backups while the server exists (az sql db list-deleted / restore --deleted-time)
  • Swap the restored database in, then bring it under management with an import block (Terraform 1.5+) or terraform import until plan shows no changes
  • Root causes: refactor without a moved block, a ForceNew attribute change, or portal drift the plan tried to correct
  • Gate: save the plan, apply exactly that file, fail or require extra approval when terraform show -json contains deletes
  • Terraform lifecycle: prevent_destroy on stateful resources; ignore_changes only for attributes deliberately owned elsewhere
  • Bicep equivalents: what-if as the gate, deployment stacks with denySettings and actionOnUnmanage detach, never complete mode
  • Backstops: CanNotDelete locks the pipeline cannot remove, LTR backups, scheduled drift checks, humans read-only in prod; test it all in a sandbox drill

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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-deleted shows 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 an import block or terraform 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 a moved block, 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 apply uses exactly that file. A policy step parses terraform show -json and fails if any delete or replace is present unless a named approver overrides. Stateful resources get lifecycle { prevent_destroy = true } and a CanNotDelete resource lock, which stops a delete even if the tool tries. A nightly plan -refresh-only reports 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."


Why a plan deletes a resource

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

Protections and what they stop

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

Production example

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.

🔍 What the interviewer is checking

Checks incident handling under data loss, a real understanding of how Terraform plans destroys, and layered prevention rather than 'be more careful'.

Green flags

  • Mitigates and restores first, then diagnoses
  • Knows dropped Azure SQL databases are restorable while the server exists, and the need to import afterwards
  • Names moved blocks, ForceNew attributes and drift as causes
  • Layers saved-plan review, automated delete gate, prevent_destroy, locks and drift checks

Red flags

  • Re-runs apply to fix it
  • Blames the person and adds 'review plans carefully' as the only action
  • Unaware that resource locks or backups exist

📚 Learn in depth

1. How Terraform decides to destroy

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.

2. Recovering an Azure SQL database

  • Automated backups (full weekly, differential every 12 or 24 hours, log about every 10 minutes) give point-in-time restore within the retention period (1–35 days; 7 by default).
  • A dropped database can be restored from those backups while the logical server exists (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.
  • The restore creates a new database; you then rename (ALTER DATABASE ... MODIFY NAME or az sql db rename) and reconnect.
  • Terraform then needs the restored database in state: an import block (Terraform 1.5+) or terraform import, followed by a clean plan.

3. Finding the cause

  1. Plan artefact from the failed run: search for must be replaced, forces replacement, will be destroyed.
  2. State history: the azurerm backend with blob versioning lets you diff the state before and after.
  3. Git diff of the refactor: look for renamed resources or new modules without moved blocks.
  4. Activity Log (Azure Monitor): who changed the database or server in the portal, and when; the delete event shows the pipeline's identity.

4. Gating destructive plans

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.

5. Defence in depth on Azure

  • 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.
  • Management locks (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).
  • Bicep: never complete mode in shared resource groups; deployment stacks with denySettings (denyDelete) and actionOnUnmanage set to detach for stateful resources; what-if (now also for stacks) as a gate.
  • Backups: long-term retention for production databases; soft delete on storage and Key Vault.

6. Drift detection

  • Nightly terraform plan -refresh-only -detailed-exitcode (exit code 2 means changes) or az deployment group what-if, alerting on any difference.
  • Activity Log alert on write operations in prod by anyone except the pipeline identity.
  • Humans Reader in prod; just-in-time elevation through Entra PIM for break-glass.

Try it yourself

  1. In a sandbox, create an azurerm_mssql_database, move it into a module without a moved block, and read the plan. Then add the block and plan again.
  2. Change the database collation in config and find # forces replacement in the plan.
  3. Delete the database, run az sql db list-deleted, and restore it with --deleted-time.
  4. Write an import block for the restored database and get the plan to 'No changes'.
  5. Add a CanNotDelete lock and try terraform destroy; read the error.
  6. Write a 10-line script that fails when terraform show -json contains any delete action.

💻 Code

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; }

⚠ Common mistakes

  • Mistake: Diagnosing before restoring. Why it is wrong: Every minute the app writes to the empty database makes reconciliation harder, and backup windows are finite. Instead: Stop pipelines, enter maintenance mode, start the restore, then investigate.
  • Mistake: Running 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.
  • Mistake: Refactoring into modules without 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.
  • Mistake: -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.
  • Mistake: Relying on 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.
  • Mistake: Using 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.
  • Mistake: Giving the pipeline Owner. Why it is wrong: It can remove locks and grant itself anything. Instead: Contributor (cannot delete locks) plus narrowly scoped role-assignment rights.
  • Mistake: Letting people change production in the portal. Why it is wrong: Drift makes plans unpredictable; a correction can become a replacement. Instead: Reader for humans, PIM for break-glass, and code changes for everything else.
  • Mistake: Using Bicep complete mode to tidy a resource group. Why it is wrong: It deletes anything not in the template, including resources another team owns. Instead: Incremental mode or deployment stacks with deny settings.
  • Mistake: Testing the new delete gate and locks for the first time in production. Why it is wrong: A misconfigured gate either blocks every deploy or lets deletes through unnoticed. Instead: Rehearse in a sandbox subscription: plan a deliberate replace, confirm the gate fails, confirm the lock blocks terraform destroy, and run a timed restore drill each quarter.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate talks about rolling back or the pipeline changes after the incident. Why: Checks how the candidate handles rollback versus roll-forward and database changes in a broken deployment more generally.
    How to answer

    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.

  2. When: Candidate mentions Activity Log alerts or Azure Policy guardrails. Why: Checks the candidate's use of Azure governance (budgets, Policy, alerts) beyond this one incident.
    How to answer

    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.

  3. When: Candidate mentions Bicep what-if or deployment stacks. Why: Checks the candidate can apply the same protections when writing Bicep.
    How to answer

    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.

    • Environments differ only through .bicepparam files.
    • Every change is previewed with 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.

🛠 Real-world problems: how you handle them

Module refactor without a moved block recreates the production database
Situation
[Company]'s order service on Azure SQL in Australia East, [around 50 GB], managed by Terraform from GitHub Actions with `-auto-approve`. An engineer refactored resources into a `data` module; the week before, someone had changed the database's backup storage redundancy in the portal.
Signals
Alerts for 500s and empty order history within minutes of the deploy; Application Insights showing `Invalid object name` errors as EF Core hit a database with no tables; Activity Log showing a database delete and create by the pipeline's service principal.
Investigation
Paused the workflow and enabled maintenance mode; `az sql db list-deleted` to find the dropped database and deletion time; read the plan from the run log (`-/+ ... must be replaced`, destroy at the old address); diffed state versions in the versioned backend; checked the Git diff for missing `moved` blocks; reviewed Activity Log for the earlier portal change.
Resolution
Immediate: restored the dropped database to a point just before the delete, renamed the empty one aside and the restored one into place, replayed [N] orders captured in the [10-minute] gap from the outbox table and payment provider logs. Then added `moved` blocks and an `import` block, and confirmed the plan showed no changes before re-enabling the pipeline.
Prevention
Saved-plan workflow with a delete gate on `terraform show -json`; `prevent_destroy` and `CanNotDelete` locks on the server and database; pipeline identity reduced from Owner to Contributor; nightly `plan -refresh-only` drift alert; humans Reader in prod with PIM; quarterly restore drill; post-incident review recorded in an ADR.

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.

More in Infrastructure as Code

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me