Infrastructure as Code (Bicep)
Bicep is Microsoft's domain-specific language for declaring Azure infrastructure as code — compiled to ARM templates, reviewed like application code, and deployed repeatably across environments.
Overview
Bicep replaces raw ARM JSON with a clean declarative syntax, strong typing, native module support, and first-class IDE tooling. Infrastructure defined in Bicep is committed to source control, reviewed in pull requests, promoted through environments with parameter files, and deployed by CI/CD pipelines using the Azure CLI or Azure Developer CLI. Deployment stacks extend this model by tracking which resources a deployment owns and cleaning up orphaned resources when the stack is updated or deleted. For .NET teams, Bicep pairs naturally with the azd CLI that Aspire uses for cloud deployments.
What you will learn
- Explain how Bicep compiles to ARM deployments and resource-provider APIs.
- Use scopes, symbolic references, existing resources, modules, parameters, and outputs.
- Create reusable typed modules and distribute them with version discipline.
- Protect identities, secrets, network boundaries, and deployment permissions.
- Preview, validate, deploy, observe, and troubleshoot Azure changes.
- Choose deployment stacks and ownership behavior deliberately.
Prerequisites
- Azure resource groups, identities, RBAC, networking, and resource-provider fundamentals.
- Basic declarative IaC and Git review experience.
- Azure CLI with Bicep support for optional compile and what-if exercises.
When to use Infrastructure as Code (Bicep)
Good fit
- Azure is the target platform and first-party type coverage is valuable.
- Teams need concise modules that compile directly to ARM templates.
- Deployment stacks, what-if, template specs, or Bicep registries fit the operating model.
Choose another approach when
- The same module must manage substantial non-Azure infrastructure.
- A higher-level platform already owns infrastructure and direct resource control would duplicate responsibility.
- The organization cannot operate Azure scope, policy, identity, and deployment ownership safely.
Key concepts
A Bicep file describes the desired state of Azure resources — their type, SKU, location, properties, and dependencies. The platform reconciles current state to match the declaration on each deployment.
A module is a reusable Bicep file that accepts parameters and encapsulates one cohesive set of resources — a module for a Container App, a module for a Key Vault, a module for a SQL server — composable into larger deployments.
Bicepparam files supply environment-specific values — SKUs, capacities, feature flags, connection strings — keeping the template logic environment-neutral and the differences version-controlled and reviewable.
A deployment stack tracks all resources deployed as a unit and applies a deny-assignment to prevent out-of-band changes. Updating or deleting the stack reconciles or removes managed resources automatically.
Target scope, existing resources, symbolic names, and module outputs express ownership and ordering without manually writing dependsOn arrays.
Resource schemas, decorators, compile-time validation, lint rules, and editor completion catch many deployment mistakes before Azure is contacted.
Private module registries and template specs distribute approved modules with immutable versions across teams and subscriptions.
What-if previews control-plane changes while ARM deployment records provide operation status, correlation, and audit evidence.
Architecture
Bicep source is compiled and deployed through a CI/CD pipeline, promoting one validated template with environment-specific parameters from dev through staging to production.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
The Bicep Container App Platform composes observability, environment, and workload modules with typed parameters, secure runtime input, managed identity, encrypted ingress, probes, scaling, tags, and local contract tests.
- 01Choose scope and ownership
Select tenant, management group, subscription, resource group, or extension scope and decide whether a stack owns deletion.
- 02Define typed parameters
Use descriptions, decorators, allowed values, secure inputs, and environment-neutral defaults.
- 03Model symbolic resources
Use explicit API versions and symbolic references so dependencies and type checking emerge from real data flow.
- 04Extract cohesive modules
Give modules narrow responsibilities, stable inputs, useful non-secret outputs, and versioned publication.
- 05Inject identity and secrets
Use workload identity for deployment and managed identity plus Key Vault references for runtime access.
- 06Compile and lint
Build Bicep to ARM JSON, treat diagnostics as errors, and run organization policy and security checks.
- 07Preview and deploy
Review what-if, apply through protected environments, retain deployment operations, and run workload smoke checks.
- 08Operate modules and stacks
Track API and module upgrades, drift, policy changes, resource ownership, removal behavior, and recovery.
Code example
A focused Bicep module deploys a Container App with managed identity, Key Vault secret reference, and environment-linked configuration — accepting only the values that change per environment.
// modules/container-app.bicep
@description('Name of the Container App')
param appName string
@description('Container Apps Environment resource ID')
param environmentId string
@description('Container image including tag')
param image string
@description('Key Vault URI for secret references')
param keyVaultUri string
@allowed(['dev', 'test', 'prod'])
param environment string
resource identity 'Microsoft.ManagedIdentity/userAssignedIdentities@2023-01-31' = {
name: '${appName}-identity'
location: resourceGroup().location
}
resource app 'Microsoft.App/containerApps@2024-03-01' = {
name: appName
location: resourceGroup().location
identity: {
type: 'UserAssigned'
userAssignedIdentities: { '${identity.id}': {} }
}
properties: {
environmentId: environmentId
configuration: {
ingress: { external: true, targetPort: 8080 }
secrets: [
{
name: 'db-connection'
keyVaultUrl: '${keyVaultUri}secrets/db-connection'
identity: identity.id
}
]
}
template: {
containers: [
{
name: appName
image: image
env: [
{ name: 'ASPNETCORE_ENVIRONMENT', value: environment }
{ name: 'ConnectionStrings__Database', secretRef: 'db-connection' }
]
resources: { cpu: json('0.5'), memory: '1Gi' }
}
]
scale: {
minReplicas: environment == 'prod' ? 1 : 0
maxReplicas: 10
}
}
}
}
output appUrl string = 'https://${app.properties.configuration.ingress.fqdn}'Testing strategy
Validate authoring semantics, compiled contracts, Azure control-plane effects, and workload outcomes.
- Compile every entry point and fail on diagnostics.
- Lint for secrets, hardcoded locations, unsafe defaults, and stale API versions.
- Test module parameter and output contracts.
- Review what-if at the intended target scope.
- Deploy representative configurations to an isolated subscription.
- Verify policy, identity, network, observability, removal, and rollback behavior.
Security considerations
Bicep improves authoring but ARM scope, identity, policy, and secret behavior still define risk.
- Use OIDC workload identity with the narrowest deployment role and scope.
- Mark secret parameters secure but prefer Key Vault references over raw values.
- Keep secrets out of outputs, deployment names, tags, and logs.
- Use managed identity and data-plane roles for applications.
- Enforce policy, private networking, diagnostic settings, and approved module sources.
- Review role assignments and deny-assignment implications separately from resources.
Performance and scalability
Deployment speed and reliability improve when modules and dependency graphs remain deliberate.
- Use symbolic references to enable safe parallel deployment.
- Avoid one enormous template whose unrelated resources share a failure boundary.
- Keep module nesting and outputs focused.
- Use stable deployment names when history semantics require them.
- Measure slow resource providers and long-running operations.
- Avoid unnecessary list functions and cross-scope queries.
Deployment and operations
Promote the same reviewed Bicep and module versions while parameters vary by environment.
- Compile and validate before cloud authentication is granted.
- Run what-if with the protected deployment identity.
- Require approval for deletes, replacements, role changes, public access, and SKU changes.
- Use deployment stacks when declarative removal ownership is required.
- Retain deployment operations and correlation IDs.
- Run post-deployment identity, health, policy, and connectivity tests.
Common problems and fixes
Compilation reports a property is invalid.
Likely cause: The chosen resource API version has a different schema.
Fix: Inspect the resource reference, select a supported API version, and update properties deliberately.
A module deploys before its dependency.
Likely cause: No symbolic data reference expresses the real relationship.
Fix: Pass the dependency resource ID or output, or add dependsOn only when no data dependency exists.
What-if shows noisy changes every run.
Likely cause: The provider normalizes defaults or returns runtime-only values.
Fix: Inspect the actual API behavior, specify stable values, and document justified noise rather than ignoring all changes.
Deployment fails with authorization despite Contributor.
Likely cause: Role assignments, policy, data actions, or cross-scope operations need different permissions.
Fix: Identify the exact denied action and scope, then grant the narrowest required role to the workload identity.
A secure parameter appears in deployment history.
Likely cause: It was copied into a non-secure output, tag, property, or log.
Fix: Rotate it, remove the exposure path, and use Key Vault or managed identity references.
Removing a resource from Bicep does not delete it.
Likely cause: Incremental deployment does not imply ownership-based deletion.
Fix: Use a deployment stack with explicit action-on-unmanage behavior or perform a separately reviewed retirement.
Best practices
- Treat Bicep files as production code — review them in pull requests, lint with the Bicep linter, and enforce no-hardcoded-secrets and explicit API versions as CI checks.
- Use modules to encapsulate cohesive resource groups — a Container App module, a networking module — and compose them in a main.bicep rather than putting everything in one large file.
- Separate environment-specific values into Bicepparam files and keep template logic environment-neutral so the same compiled template is promoted from dev to prod without modification.
- Run what-if deployments in CI before applying to staging or production so reviewers can see exactly which resource properties will change before approving the pipeline run.
- Pin module versions and API versions, and update them through reviewed compatibility tests.
- Use workload identity with least-privilege deployment roles and keep secrets out of source, outputs, and logs.
Production checklist
- Scope, ownership, and removal behavior are explicit.
- Parameters are typed, documented, validated, and secret-safe.
- Modules are cohesive, versioned, tested, and from approved registries.
- API versions and compile diagnostics are controlled.
- Deployment and runtime identities are least privilege.
- What-if, policy, security, and cost evidence gate deployment.
- Operations, correlation IDs, and post-deployment checks are retained.
- Stack deletion, module upgrade, and recovery paths are rehearsed.
Common interview questions
What is the difference between an ARM template and a Bicep file?
A Bicep file is a higher-level declarative language that compiles to an ARM JSON template. Bicep provides cleaner syntax, type safety, native modules, string interpolation, conditional expressions, and IDE tooling, while ARM JSON is verbose and error-prone to write by hand. The compiled output is identical — Bicep is a transparent abstraction over ARM.
What is a Bicep deployment stack and when would you use it?
A deployment stack tracks all resources deployed as a unit and can apply deny-assignments to prevent out-of-band changes to managed resources. When the stack is updated, resources removed from the template can be detached, deleted, or left in place according to the configured cleanup policy. It is useful when you want the infrastructure definition to be the authoritative source and prevent drift from manual portal changes.
How do you pass secrets into a Bicep deployment without hardcoding them?
Reference secrets from Azure Key Vault using a Bicepparam file with a getSecret() call — this injects the secret value at deployment time from Key Vault without it appearing in source control, pipeline logs, or the compiled template. The deployment identity needs Key Vault Secrets User access on the vault.
How does Bicep determine deployment order?
Symbolic resource references and module outputs create implicit dependencies; use explicit dependsOn only when no data reference expresses the real ordering.
What is an existing resource in Bicep?
The existing keyword references a resource managed elsewhere without redeploying it, allowing modules to read identifiers and properties at the correct scope.
How should reusable Bicep modules be distributed?
Publish versioned modules to a private Bicep registry or template specs, document contracts, test compiled output, and upgrade consumers deliberately.
What can make what-if incomplete?
Runtime values, provider behavior, policy, permissions, quota, extension resources, and unsupported change analysis can produce noise or unknown results, so what-if is evidence rather than a guarantee.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
Bicep Container App Platform
A modular Azure Container Apps deployment demonstrating typed parameters, secure inputs, observability, managed identity, ingress, probes, scaling, tags, and local Bicep contract tests.
- Run
dotnet run --project tools/BicepContract -- infra- Test
dotnet test BicepContainerAppPlatform.slnx