Terraform
Terraform describes infrastructure—networks, databases, compute, permissions—as declarative configuration, then plans and applies the changes needed to make real infrastructure match that configuration.
Overview
A provider maps Terraform's HCL configuration to versioned platform APIs, so one workflow can manage Azure, AWS, SaaS, and other systems. Terraform refreshes remote objects into protected state, builds a dependency graph, and computes a plan showing creates, updates, replacements, and destroys before any change is applied. Teams use typed variables, validation, modules, outputs, remote backends, locking, imports, and moved blocks to manage infrastructure throughout its lifecycle. Production practice also requires pinned providers, reviewed saved plans, short-lived identity, policy checks, drift ownership, secret-safe state, and recovery procedures.
What you will learn
- Explain providers, configuration, state, graph planning, and apply behavior.
- Design protected remote-state and locking boundaries.
- Create reusable typed modules without hiding important decisions.
- Import, move, replace, and retire resources safely.
- Secure provider identity, state, plans, variables, and outputs.
- Operate Terraform through reviewed plans, policy gates, drift detection, and recovery.
Prerequisites
- Basic cloud resource, identity, networking, and CLI concepts.
- Familiarity with Git review and environment promotion.
- Terraform CLI and provider credentials for optional real plan exercises.
When to use Terraform
Good fit
- One workflow must manage infrastructure across multiple providers or platforms.
- Teams need explicit state, plan review, reusable modules, and lifecycle control.
- An ecosystem provider supports the required resources and maturity level.
Choose another approach when
- The target is Azure-only and first-party Bicep coverage and support are the stronger fit.
- A service-specific platform already owns provisioning and exposing raw infrastructure adds risk.
- State ownership, identity, review, and recovery cannot be operated responsibly.
Key concepts
A provider translates Terraform configuration into calls against a specific platform's API, letting one tool and workflow target multiple clouds.
Terraform records the real infrastructure it manages in a state file, using it to compute the difference between desired and actual on every run.
Plan shows exactly what will be created, changed, or destroyed before anything happens; apply executes only that reviewed plan.
Reusable, parameterized configuration packages let teams share a tested infrastructure shape—like a standard app environment—instead of duplicating raw resources.
References between resources create a dependency graph that Terraform evaluates in parallel where safe and in order where required.
Refresh, import, moved blocks, lifecycle rules, and replacement semantics control how configuration converges with infrastructure that already exists.
Typed inputs, validation, locals, and non-sensitive outputs make configuration reusable without hiding important environment decisions.
A remote backend protects shared state, coordinates locking, controls access, and provides recovery history for team workflows.
Architecture
Configuration is planned against current state to compute a diff, then applied through the provider to create the real infrastructure.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
The Terraform Azure Web Platform provisions a .NET 10 App Service baseline with validated environments, mandatory tags, observability, managed identity, HTTPS, health checks, and a local executable contract inspector.
- 01Define ownership
Choose a state boundary whose resources share lifecycle, access, blast radius, and deployment cadence.
- 02Pin tooling
Constrain Terraform and provider versions, initialize providers, and commit the generated dependency lock file.
- 03Configure the backend
Use encrypted remote state with locking, version history, audit logs, least privilege, and tested recovery.
- 04Model typed inputs
Use descriptions, types, validation, locals, and governance tags so invalid environments fail before planning.
- 05Compose resources and modules
Express real references to build the dependency graph and keep modules cohesive with narrow contracts.
- 06Plan with evidence
Format, validate, refresh, run policy and security checks, and publish a saved plan for review.
- 07Apply through automation
Use short-lived identity, environment approval, concurrency control, the reviewed plan artifact, and retained logs.
- 08Operate lifecycle
Detect drift, import existing objects, use moved blocks for refactoring, rehearse state recovery, and retire resources deliberately.
Code example
A module call provisions a standard app environment with parameters instead of duplicating the underlying resources per project.
module "orders_api" {
source = "./modules/app-service"
name = "orders-api"
resource_group_name = azurerm_resource_group.main.name
sku_name = "P1v3"
app_settings = {
ASPNETCORE_ENVIRONMENT = "Production"
}
}
output "orders_api_url" {
value = module.orders_api.default_hostname
}Testing strategy
Terraform evidence progresses from static configuration checks to plans and ephemeral deployment tests.
- Run fmt and validate for every change.
- Execute module contract and policy tests.
- Inspect the full saved plan including replacements and destroys.
- Test representative modules in an isolated subscription or account.
- Verify outputs, identity, security posture, and observability after apply.
- Exercise import, move, rollback, and state recovery procedures.
Security considerations
Configuration, state, plans, providers, and the apply identity are all supply-chain or control-plane assets.
- Use workload identity and least-privilege provider roles.
- Encrypt and tightly restrict remote state and plan artifacts.
- Never assume sensitive variables prevent values from entering state.
- Pin providers and modules and review their provenance.
- Run static, policy, dependency, and cloud-posture checks.
- Separate untrusted plan jobs from protected apply credentials.
Performance and scalability
Fast predictable plans depend on sensible state boundaries and provider behavior.
- Split state by lifecycle and blast radius rather than individual resource.
- Avoid broad data-source queries and unnecessary cross-state reads.
- Allow safe graph parallelism but respect provider throttling.
- Cache providers in CI from the lock file.
- Measure plan and apply duration and investigate unexpected growth.
- Do not use targeted applies as a routine performance shortcut.
Deployment and operations
Promote reviewed configuration and saved-plan evidence through controlled environments.
- Run speculative plans for pull requests without apply credentials.
- Re-plan after merge against current protected state.
- Require approval for destroy, replacement, privilege, and network exposure changes.
- Serialize applies per state and retain deployment evidence.
- Run post-apply security and workload smoke checks.
- Prefer forward repair while retaining state-version and provider recovery procedures.
Common problems and fixes
State lock remains after a failed run.
Likely cause: The client exited without releasing the backend lock.
Fix: Confirm no apply is active, inspect lock ownership, then use force-unlock with the exact lock ID.
Plan wants to recreate an existing resource.
Likely cause: Its address, identifier, immutable property, or provider interpretation changed.
Fix: Inspect the replacement reason and use import or moved blocks only when ownership and identity are verified.
Manual changes keep disappearing.
Likely cause: Out-of-band drift conflicts with configuration.
Fix: Decide the authoritative desired state, update configuration or revert drift, and restrict manual writes.
A sensitive value appears in state.
Likely cause: Sensitive affects display, not provider persistence.
Fix: Rotate the value, restrict state, redesign the resource to reference a secret, and remove historical exposure safely.
Provider upgrade changes many resources.
Likely cause: Schema, defaults, normalization, or behavior changed.
Fix: Pin versions, read the upgrade guide, test in isolation, and upgrade in a dedicated reviewed change.
Apply differs from the reviewed proposal.
Likely cause: A new plan was generated or state changed after review.
Fix: Apply the reviewed saved plan promptly or regenerate and require a new review.
Best practices
- Store state remotely with locking so two runs can't apply conflicting changes to the same infrastructure at once.
- Always review a plan's output before applying it, especially destroy actions—treat plan as a required gate, not a formality.
- Package repeated infrastructure shapes as modules with clear inputs and outputs instead of copy-pasting resource blocks.
- Keep secrets out of state and configuration; reference them from a secrets manager instead of hardcoding values.
- Pin Terraform and provider versions and commit the dependency lock file.
- Use workload identity, least-privilege cloud roles, policy checks, and an audited apply pipeline.
Production checklist
- State boundary and ownership are explicit.
- Remote state is encrypted, locked, versioned, audited, and recoverable.
- Terraform, providers, and modules are pinned.
- Inputs are typed and validated; outputs exclude credentials.
- Plan, policy, security, and cost evidence gate apply.
- Apply identity is short-lived and least privilege.
- Import, move, drift, and deletion procedures are tested.
- Every apply is serialized, observable, attributable, and recoverable.
Common interview questions
What is Terraform state, and why does losing it matter?
State is Terraform's record of the real infrastructure it manages, used to compute what's changed on every run; without it, Terraform has no way to know what already exists and can plan to recreate or orphan real resources.
Why review a Terraform plan before applying it?
The plan shows exactly what will be created, changed, or destroyed as a result of a configuration change, catching unintended consequences—like a destroy triggered by a renamed resource—before they happen against real infrastructure.
What problem do Terraform modules solve?
They let a team package a tested, parameterized shape of infrastructure—like a standard app environment—and reuse it across projects, instead of every project hand-writing and maintaining its own copy of similar resource blocks.
What is infrastructure drift?
Drift is a difference between configuration, recorded state, and real provider state, often caused by manual changes or external automation; refresh and plan reveal its likely reconciliation.
When should terraform import be used?
Import associates an existing remote object with a resource address so it can be brought under management after matching configuration is written and reviewed.
Why save a plan artifact?
Applying the reviewed saved plan ensures the executed change is the same proposal reviewers approved, provided state and provider constraints remain valid.
How should Terraform state be protected?
Use an encrypted remote backend, locking, version history, least-privilege access, audit logs, backups, and careful treatment because state can contain sensitive values.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
Terraform Azure Web Platform
A governed Azure App Service platform demonstrating provider constraints, validated inputs, tags, observability, managed identity, HTTPS, health checks, outputs, and executable Terraform contract tests.
- Run
dotnet run --project tools/TerraformContract -- infra- Test
dotnet test TerraformAzureWebPlatform.slnx