Azure Bicep Tutorial: Infrastructure as Code
On this page
Learning Objective
Describe the Azure environment declaratively in Bicep with parameters and modules, preview changes with what-if, deploy through the pipeline with least-privilege federated identity, keep secrets out of templates and outputs, and encode security baselines so they cannot drift.
Concept Explanation
Click-built environments cannot be reviewed, reproduced, or trusted. Nobody remembers which checkbox was ticked, staging and production diverge, and a disaster recovery plan that begins with recreating everything by hand is not a plan. Infrastructure as code fixes this by describing resources in text files under version control, so changes go through pull requests, the environment can be rebuilt in minutes, and the differences between staging and production are visible as differences in a small set of parameters. For a security-conscious team it is even more valuable: the hardening you decided on, private endpoints, TLS versions, managed identities, and diagnostic logging, is written down once and applied every time.
Bicep is Azure's own language for this. Announced in 2020 as a more readable layer over ARM templates, it compiles to them, supports every Azure resource as soon as it is released, and offers a compact syntax with parameters, variables, loops, conditions, and modules. A module packages a group of related resources, such as a web app with its identity and diagnostics, with a defined set of inputs and outputs, so environments compose them. Terraform, from HashiCorp, is the multi-cloud alternative with its own language and state file, and after HashiCorp moved it to a source-available license in 2023, the community created the OpenTofu fork; for an Azure-only product Bicep is simple and has no state file to protect, since Azure Resource Manager is the source of truth.
The workflow has three habits. Preview before applying: the what-if operation compares the template to the live environment and shows exactly what would be created, modified, or deleted, and it belongs in the pull request as a review artifact. Deploy from the pipeline, never from laptops, using the OIDC federated identity of Day 83, with a role scoped to the resource group and only as broad as the deployment needs, which is why separating infrastructure from application deployment identities is worthwhile. And guard against drift: if someone changes a resource in the portal, the next deployment overwrites it, or a periodic what-if job reports it, so the code stays the truth. Deployment stacks add protection by preventing unmanaged changes to and deletion of the resources they manage.
Secrets and security baselines need explicit care. Mark secret parameters with the secure decorator so they are not logged in deployment history, and prefer not to pass secrets at all: use managed identities, Key Vault references, and generated values that stay inside Azure. Never output a secret from a template, since outputs are stored in the deployment history readable by anyone with reader access to it. Encode baselines as defaults inside your modules, for example HTTPS only, minimum TLS 1.2, public network access disabled, soft delete and purge protection on vaults, diagnostic settings on everything, and resource locks on production databases to prevent accidental deletion. Add automated policy checks, such as Azure Policy assignments that deny non-compliant resources and a scanner like PSRule for Azure or Checkov in the pipeline, so a template that weakens a baseline fails review.
| Concern | Practice | Reason |
|---|---|---|
| Reproducibility | Whole environment in Bicep in the repository | Rebuild and review changes as code |
| Environments | Same modules, different parameter files | Differences are visible and small |
| Preview | az deployment what-if in the pull request | See changes and deletions before they happen |
| Deploy identity | OIDC federation, role scoped to the resource group | No stored secret, limited blast radius |
| Secrets | Secure parameters, Key Vault, never in outputs | Deployment history is readable |
| Baselines and guardrails | Secure defaults in modules, Azure Policy, template scanning, locks | Drift and weakening are caught automatically |
Worked Example: A Module, an Environment File, What-If and a Policy Guard
The main template composes modules for the data and web tiers, the module encodes secure defaults, and the commands preview and deploy.
// infra/main.bicep
targetScope = 'resourceGroup'
@allowed(['staging', 'production'])
param environment string
param location string = resourceGroup().location
param sqlAdminGroupObjectId string // an Entra group, not a person, administers the database
param frontDoorId string
var suffix = uniqueString(resourceGroup().id)
var tags = { app: 'taskboard', env: environment, owner: 'platform-team' }
module monitoring 'modules/monitoring.bicep' = { name: 'monitoring', params: { location: location, suffix: suffix, tags: tags } }
module data 'modules/data.bicep' = {
name: 'data'
params: { location: location, suffix: suffix, tags: tags, sqlAdminGroupObjectId: sqlAdminGroupObjectId
logWorkspaceId: monitoring.outputs.workspaceId, lockProduction: environment == 'production' }
}
module web 'modules/web.bicep' = {
name: 'web'
params: { location: location, suffix: suffix, tags: tags, frontDoorId: frontDoorId, logWorkspaceId: monitoring.outputs.workspaceId
keyVaultName: data.outputs.keyVaultName, sqlServerFqdn: data.outputs.sqlServerFqdn
planSku: environment == 'production' ? 'P1v3' : 'B2', minInstances: environment == 'production' ? 3 : 1 }
}
output webHostname string = web.outputs.hostname // fine to output. Never output secrets or connection strings with passwords.// infra/modules/data.bicep: secure by default, so every environment inherits it.
param location string
param suffix string
param tags object
param sqlAdminGroupObjectId string
param logWorkspaceId string
param lockProduction bool
resource kv 'Microsoft.KeyVault/vaults@2023-07-01' = {
name: 'kv-tb-${suffix}'
location: location
tags: tags
properties: {
sku: { family: 'A', name: 'standard' }
tenantId: subscription().tenantId
enableRbacAuthorization: true // roles, not access policies
enableSoftDelete: true
enablePurgeProtection: true
publicNetworkAccess: 'Disabled'
networkAcls: { defaultAction: 'Deny', bypass: 'AzureServices' }
}
}
resource sql 'Microsoft.Sql/servers@2023-08-01-preview' = {
name: 'sql-tb-${suffix}'
location: location
tags: tags
properties: {
minimalTlsVersion: '1.2'
publicNetworkAccess: 'Disabled' // reachable only through a private endpoint
administrators: {
administratorType: 'ActiveDirectory'
azureADOnlyAuthentication: true // no SQL logins and no passwords at all
principalType: 'Group'
sid: sqlAdminGroupObjectId
tenantId: subscription().tenantId
login: 'sql-admins'
}
}
}
resource db 'Microsoft.Sql/servers/databases@2023-08-01-preview' = {
parent: sql
name: 'TaskBoard'
location: location
tags: tags
sku: { name: 'GP_S_Gen5_2', tier: 'GeneralPurpose' }
properties: { zoneRedundant: false }
}
resource sqlAudit 'Microsoft.Sql/servers/auditingSettings@2023-08-01-preview' = {
parent: sql
name: 'default'
properties: { state: 'Enabled', isAzureMonitorTargetEnabled: true }
}
resource kvDiag 'Microsoft.Insights/diagnosticSettings@2021-05-01-preview' = {
scope: kv
name: 'audit'
properties: { workspaceId: logWorkspaceId, logs: [{ category: 'AuditEvent', enabled: true }] }
}
resource lock 'Microsoft.Authorization/locks@2020-05-01' = if (lockProduction) {
scope: db
name: 'do-not-delete'
properties: { level: 'CanNotDelete', notes: 'Production database. Remove the lock deliberately, in code review.' }
}
output keyVaultName string = kv.name
output sqlServerFqdn string = sql.properties.fullyQualifiedDomainName# infra/parameters/production.bicepparam
using '../main.bicep'
param environment = 'production'
param sqlAdminGroupObjectId = '00000000-0000-0000-0000-000000000000' // a group id, not a secret
param frontDoorId = '11111111-1111-1111-1111-111111111111'# Preview in the pull request: what would change, including deletions, before anything is applied.
az deployment group what-if -g rg-taskboard-prod --template-file infra/main.bicep --parameters infra/parameters/production.bicepparam
# Deploy from the pipeline with the federated identity (Contributor on this resource group only).
az deployment group create -g rg-taskboard-prod --template-file infra/main.bicep \
--parameters infra/parameters/production.bicepparam --name "infra-$GITHUB_SHA"
# Scan the templates for insecure settings as a required check.
docker run --rm -v "$PWD:/src" bridgecrew/checkov -d /src/infra --framework bicep --quiet// A guardrail that lives in Azure itself: deny any storage account that allows public blob access.
resource denyPublicBlob 'Microsoft.Authorization/policyAssignments@2022-06-01' = {
name: 'deny-public-blob'
properties: {
displayName: 'Storage accounts must not allow public blob access'
policyDefinitionId: '/providers/Microsoft.Authorization/policyDefinitions/4fa4b6c0-31ca-4c0d-b10d-24b96f62a751'
enforcementMode: 'Default'
}
}The what-if output is the most important review artifact. A change that unexpectedly shows a delete or a recreate of the database is exactly the kind of mistake it exists to catch, and the CanNotDelete lock is the second line of defense.
Real-World Examples
- Microsoft introduced Bicep in 2020 as a domain-specific language for deploying Azure resources, addressing the verbosity of JSON ARM templates, and it reached general availability for use in production as a first-class Azure tool the following year. Because it compiles to ARM templates and is supported by the platform itself, new Azure features are available in Bicep from day one.
- In August 2023 HashiCorp changed Terraform's license from open source to the Business Source License, and a group of companies responded by forking it as OpenTofu under the Linux Foundation. The episode is a reminder that tooling choices carry licensing and governance risk, and part of the appeal of Bicep for Azure-only teams is its lack of a separate state file and its vendor-native support.
Review Questions & Answers
It compares the template with the actual deployed environment and shows the resulting changes, including resources that would be modified, recreated, or deleted, which the text diff alone cannot reveal. It catches surprises such as an innocuous-looking property change that forces a database to be recreated.
Deployment outputs are stored in the deployment history, which anyone with read access to the resource group can view, so a secret output is exposed to a wider audience than the secret store intends. Secrets should be generated or referenced inside Azure, for example through Key Vault and managed identity, and never returned.
Every environment built from the module inherits the hardened configuration, such as TLS 1.2, disabled public access, purge protection, and audit logging, without depending on people to remember each setting. A weakening then requires a deliberate, reviewable change to the module, which policy and scanners can flag.
A dedicated federated identity with a role limited to one resource group can be audited and revoked independently, has no standing credentials to steal, and cannot affect other resource groups if compromised. Personal accounts with broad rights and manual deployments are harder to audit and much riskier.