Volume 8 · Chapter 8 — Azure Cloud Architecture & Enterprise DevOps for .NET Engineers
Infrastructure as Code with Terraform and Bicep
8.1 Introduction
Infrastructure as Code (IaC) means defining cloud infrastructure in version-controlled, declarative files and provisioning it through automation rather than clicking through portals. It brings software-engineering discipline - review, versioning, testing, repeatability - to infrastructure, eliminating the configuration drift and snowflake environments that plague manually managed estates. For a regulated enterprise, IaC is also how you make infrastructure auditable and disaster-recoverable: the environment can be rebuilt from code.
8.2 Declarative and Idempotent
IaC tools are declarative: you describe the desired end state, and the tool computes the changes needed to reach it. This makes them idempotent - applying the same definition repeatedly converges to the same result, whether creating from scratch or correcting drift. That is fundamentally more reliable than imperative scripts that assume a starting state.
sequenceDiagram autonumber participant Dev as Engineer participant Repo as Git (IaC) participant CI as Pipeline participant Tool as Terraform/Bicep participant Azure as Azure Dev->>Repo: PR with infra change Repo->>CI: validate + plan (what will change) CI-->>Dev: plan reviewed in PR Dev->>Repo: approve + merge Repo->>CI: apply CI->>Tool: reconcile desired vs actual Tool->>Azure: create/update/delete resources Azure-->>Tool: state updated
8.3 Azure Bicep
Bicep is Azure’s native IaC language - a clean, typed DSL that compiles to ARM templates. It has first-class Azure support (new resource types available immediately), no state file to manage (it uses Azure’s deployment engine as the source of truth), and readable modular syntax. It is the natural choice for Azure-only estates.
// Bicep: a reusable, parameterized module for an App Service with managed identity.
param location string = resourceGroup().location
param appName string
resource plan 'Microsoft.Web/serverfarms@2023-01-01' = {
name: '${appName}-plan'
location: location
sku: { name: 'P1v3' }
}
resource app 'Microsoft.Web/sites@2023-01-01' = {
name: appName
location: location
identity: { type: 'SystemAssigned' } // managed identity, no secrets
properties: { serverFarmId: plan.id, httpsOnly: true }
}
output principalId string = app.identity.principalId
8.4 Terraform
Terraform is a cloud-agnostic IaC tool using the HCL language and a provider model that supports Azure, AWS, GCP, and hundreds of other systems. It is the standard for multi-cloud organizations and for teams wanting one tool and workflow across providers. Its defining feature - and its main operational responsibility - is the state file.
8.5 State Management
Terraform records what it has provisioned in a state file, which it diffs against your configuration to plan changes. This state is critical infrastructure: it must be stored remotely (in an Azure Storage backend), locked during operations to prevent concurrent corruption, secured (it can contain secrets), and backed up. Bicep sidesteps this by using Azure itself as the state store, which is a genuine simplicity advantage on Azure-only estates.
8.6 Modules and Reuse
The key to IaC at scale is modularity: reusable modules encode a golden, compliant pattern for a component - a hardened VNet, a private-endpoint-enabled SQL, an AKS cluster - so every team provisions to the same secure standard. Modules turn architectural standards into executable, versioned building blocks.
8.7 Environments and the Plan/Apply Gate
The same modules parameterized per environment produce consistent dev, test, and production infrastructure that differ only in configuration (sizes, counts). The plan/apply workflow is the crucial safety gate:planshows exactly what will change and is reviewed in a pull request, and only after approval doesapplyexecute - so infrastructure changes get the same scrutiny as code, and surprises are caught before they hit production.
8.8 IaC Security and Governance
Secrets never live in IaC files - reference Key Vault instead. IaC scanning (Checkov, tfsec, PSRule for Bicep) catches insecure configurations before apply, and Azure Policy enforces guardrails at the platform level (allowed regions, required tags, mandated private endpoints) that IaC must satisfy. Pipelines run IaC with least-privilege workload identity, not stored credentials.
Why is Infrastructure as Code important?
Because it makes infrastructure repeatable, reviewable, and reliable instead of manual and drift-prone. Defining infrastructure declaratively in version control means every change is peer-reviewed, versioned, and auditable; environments are reproduced identically from the same code, eliminating snowflake servers and “works in one environment” surprises; and disaster recovery becomes “re-run the code” rather than hoping someone remembers the manual steps. IaC is idempotent, so re-applying converges to the desired state and corrects drift. For regulated enterprises it also provides the audit trail and consistency that compliance demands. In short, it applies software-engineering discipline to infrastructure, which is what makes cloud estates manageable at scale.
How do you decide between Bicep and Terraform?
Primarily by whether you are Azure-only or multi-cloud, and by team preference. Bicep is Azure-native: it supports new Azure resource types the day they ship, needs no state file to manage (Azure is the source of truth), has clean typed syntax, and integrates tightly with Azure tooling - making it the low-friction choice for Azure-only estates. Terraform is cloud-agnostic with a huge provider ecosystem, so it is the choice for multi-cloud or hybrid environments or organizations standardizing one IaC workflow across providers, at the cost of owning state management. If everything is on Azure and the team has no multi-cloud need, Bicep is usually simpler; if there is multi-cloud, existing Terraform investment, or a desire for one tool everywhere, Terraform wins.
Why is Terraform state so important, and how do you manage it safely?
Terraform’s state file is its record of the real resources it manages; it diffs state against your configuration to compute the plan, so a lost or corrupted state can make Terraform try to recreate or orphan infrastructure. It also frequently contains sensitive values. Safe management means storing it in a remote backend (such as an Azure Storage account) rather than locally, enabling state locking so two runs cannot mutate it concurrently and corrupt it, securing access to it (encryption, least-privilege) because of the secrets it holds, and backing it up / versioning it. Teams also isolate state per environment/component to limit blast radius. Bicep avoids this class of problem entirely by using Azure’s own deployment state, which is one of its operational advantages on Azure-only estates.
What is the value of the plan/apply workflow?
It is the safety gate that makes infrastructure change reviewable before it happens.plan(or a Bicep what-if) computes and shows exactly which resources will be created, changed, or - critically - destroyed, without making any change. That output is reviewed in a pull request just like code, so a reviewer can catch a change that would delete a production database or open a firewall before it executes. Only after approval doesapplyperform precisely those changes. This turns infrastructure modifications from risky, opaque, direct actions into transparent, peer-reviewed, predictable operations, and it is the mechanism that lets teams trust automation with production infrastructure.
How do you design an enterprise IaC practice that keeps dozens of teams compliant without slowing them down?
I combine reusable golden modules with platform-level policy enforcement. The modules encode compliant patterns - a VNet with the right segmentation, SQL with private endpoints and encryption, an AKS baseline - so teams provision secure infrastructure by consuming a versioned module rather than assembling raw resources and getting security wrong. Azure Policy provides a backstop that enforces non-negotiables (allowed regions, required tags, mandatory private endpoints, no public storage) regardless of what code is written, so guardrails hold even outside the modules. IaC runs through pipelines with plan-review gates, IaC security scanning, remote/locked state (or Bicep), and least-privilege workload identity. I isolate state and blast radius per environment and component, and I version modules so upgrades are controlled. The result is a self-service model: teams move fast using approved building blocks, while compliance is guaranteed by modules plus policy rather than by manual review of every change. Guardrails, not gates, keep both speed and safety.
Production infrastructure has drifted from the IaC because someone made manual portal changes. How do you handle it and prevent recurrence?
First I reconcile: run a plan/what-if to see exactly how reality diverges from code, decide whether each manual change was legitimate (and should be codified) or unwanted (and should be reverted), then bring state and code back into agreement - importing legitimate changes into IaC or re-applying to overwrite unwanted ones, carefully, in a controlled window. Prevention is the more important part and is mostly about closing the manual-change path: lock down write access so humans cannot edit production directly (RBAC that permits changes only via the pipeline’s identity, with break-glass access audited), and enforce it with policy. I add drift detection - scheduled plan runs that alert when reality diverges - so drift is caught quickly rather than discovered during an incident. Culturally, the rule is that all production changes go through IaC and review; the portal is read-only for production. Making the compliant path the only path is what prevents drift from recurring.
8.9 Banking Enterprise Scenario
A bank provisions all Azure infrastructure through IaC - Bicep for its Azure-only workloads - built from a library of golden modules that encode compliant patterns: VNets with tiered subnets and NSGs, Azure SQL with private endpoints and encryption, and hardened AKS baselines. The same modules, parameterized per environment, produce identical dev, test, and production estates. Every change flows through a pipeline that runs a what-if reviewed in the pull request, scans the IaC for insecure settings, and applies with least-privilege workload identity - no stored credentials. Azure Policy enforces allowed regions, mandatory tags, and required private endpoints as a platform backstop. Production is not editable by hand; scheduled drift detection alerts on any divergence, so the environment always matches its code and can be rebuilt for disaster recovery.
Chapter Revision Notes
- IaC makes infrastructure repeatable, reviewable, auditable, and drift-free.
- Declarative + idempotent: describe desired state, re-apply to converge.
- Bicep is Azure-native (no state file); Terraform is multi-cloud (manage state carefully).
- Reusable modules encode compliant golden patterns for scale.
- The plan/apply gate makes infrastructure change reviewable before it happens.
- Enforce compliance with modules + Azure Policy; block manual production changes.