3: Deploy and Manage Azure Compute Resources

    Automate deployment of resources by using Azure Resource Manager templates or Bicep files.

    The Problem: Manual Deployments Do Not Scale

    When you create resources through the Azure portal, you click through wizards, fill in forms, and wait for each resource to provision. This approach works for a single virtual machine or storage account, but it breaks down when you need to deploy the same environment across development, staging, and production, or when you need to recreate an environment after a disaster. Manual steps introduce human error, drift between environments, and a lack of audit trail. Infrastructure as Code (IaC) solves this by expressing your desired infrastructure in text files that can be version-controlled, reviewed, tested, and deployed automatically.

    Azure Resource Manager: The Control Plane

    Azure Resource Manager (ARM) is the deployment and management service for Azure. Every request you send to Azure, whether from the portal, CLI, PowerShell, REST API, or an SDK, travels through ARM. ARM authenticates the caller (using Microsoft Entra ID), authorizes the action (using Azure RBAC), and then routes the request to the appropriate resource provider (for example, Microsoft.Compute for virtual machines, Microsoft.Storage for storage accounts).

    Because ARM is the single entry point, the template language that ARM understands becomes the universal way to define Azure infrastructure. There are two authoring formats for ARM: JSON-based ARM templates and Bicep.

    ARM Templates (JSON)

    An ARM template is a JSON file that declares the resources you want to deploy. ARM templates use declarative syntax: you state what you want, and ARM determines how to create or update the resources. Deployments are idempotent, meaning you can deploy the same template repeatedly and the result is the same desired state each time.

    Structure of an ARM Template

    Every ARM template contains these top-level elements:

    {
     "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
     "contentVersion": "1.0.0.0",
     "parameters": {},
     "variables": {},
     "functions": [],
     "resources": [],
     "outputs": {}
    }
    
    ElementRequiredPurpose
    $schemaYesURL of the JSON schema that defines the template language version
    contentVersionYesVersion of the template content (you manage this value)
    parametersNoValues supplied at deployment time to customize the template
    variablesNoComputed values reused throughout the template to simplify expressions
    functionsNoUser-defined functions for complex expressions
    resourcesYesThe Azure resources to create or update
    outputsNoValues returned after deployment (for example, connection strings, IP addresses)

    💡 Exam Trap: The $schema value determines the deployment scope. The schema ending in deploymentTemplate.json# targets resource group deployments. For subscription-level deployments (such as creating resource groups or applying policies), you must use the schema ending in subscriptionDeploymentTemplate.json#. Using the wrong schema causes a validation failure.

    Parameters

    Parameters make templates reusable. You can constrain parameters with allowedValues, minLength, maxLength, minValue, maxValue, and defaultValue. A template supports a maximum of 256 parameters.

    "parameters": {
     "storageAccountName": {
     "type": "string",
     "minLength": 3,
     "maxLength": 24,
     "metadata": {
     "description": "Name of the storage account"
     }
     },
     "location": {
     "type": "string",
     "defaultValue": "[resourceGroup().location]"
     },
     "skuName": {
     "type": "string",
     "defaultValue": "Standard_LRS",
     "allowedValues": [
     "Standard_LRS",
     "Standard_GRS",
     "Standard_ZRS",
     "Premium_LRS"
     ]
     }
    }
    

    Parameter values can be passed inline or via a separate parameter file (.parameters.json). This lets you keep a single template but supply different parameter files per environment.

    💡 Exam Trap: Never put secrets (passwords, keys) directly in parameter files stored in source control. Use secureString or secureObject parameter types, and reference secrets from Azure Key Vault using a Key Vault parameter reference in the parameter file. ARM decrypts the secret at deployment time and never logs the value.

    Variables

    Variables reduce repetition. You can reference parameters, other variables, and template functions. A template supports a maximum of 256 variables.

    "variables": {
     "vmName": "[concat('vm-', parameters('environment'), '-01')]",
     "subnetRef": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('vnetName'), variables('subnetName'))]"
    }
    

    Resources

    The resources array is the heart of the template. Each resource object requires type, apiVersion, name, and usually location and properties.

    "resources": [
     {
     "type": "Microsoft.Storage/storageAccounts",
     "apiVersion": "2023-01-01",
     "name": "[parameters('storageAccountName')]",
     "location": "[parameters('location')]",
     "sku": {
     "name": "[parameters('skuName')]"
     },
     "kind": "StorageV2",
     "properties": {}
     }
    ]
    

    💡 Exam Trap: The apiVersion is mandatory for every resource and determines which properties and behaviors are available. Using a very old API version may not expose newer features; using a preview API version may introduce breaking changes. Always match the API version to the feature set you need.

    Outputs

    Outputs return values from a deployment, which is useful when chaining deployments or when you need to display a connection string.

    "outputs": {
     "storageEndpoint": {
     "type": "string",
     "value": "[reference(parameters('storageAccountName')).primaryEndpoints.blob]"
     }
    }
    

    Key Template Functions

    ARM templates include over 80 built-in functions grouped into categories: string functions (concat, toLower, substring), numeric functions (add, mul), comparison functions (equals, greater), logical functions (if, and, or, not), resource functions (resourceId, reference, resourceGroup, subscription), and deployment functions (deployment). The reference() function retrieves the runtime state of a deployed resource and can only be used in the resources and outputs sections.

    Deploying an ARM Template

    # Azure CLI - deploy to a resource group
    az deployment group create \
     --resource-group myResourceGroup \
     --template-file azuredeploy.json \
     --parameters azuredeploy.parameters.json
    
    # PowerShell - deploy to a resource group
    New-AzResourceGroupDeployment `
     -ResourceGroupName myResourceGroup `
     -TemplateFile azuredeploy.json `
     -TemplateParameterFile azuredeploy.parameters.json
    

    Deployment Scopes

    ARM template deployments target one of four scopes:

    ScopeCLI CommandSchema Suffix
    Resource groupaz deployment group createdeploymentTemplate.json#
    Subscriptionaz deployment sub createsubscriptionDeploymentTemplate.json#
    Management groupaz deployment mg createmanagementGroupDeploymentTemplate.json#
    Tenantaz deployment tenant createtenantDeploymentTemplate.json#

    Deployment Modes: Incremental vs. Complete

    ARM supports two deployment modes that control how existing resources in the target resource group are handled.

    Incremental mode (the default) adds or updates resources defined in the template but leaves resources not mentioned in the template untouched. This is the safer, recommended mode.

    Complete mode adds or updates resources defined in the template and deletes any resources in the resource group that are not in the template. This is powerful for enforcing drift correction but dangerous if you forget to include a resource.

    💡 Exam Trap: The Azure portal always deploys in incremental mode; it does not support complete mode. Complete mode is only available through CLI, PowerShell, and REST API. Also, linked or nested templates always run in incremental mode regardless of the parent template's mode. Subscription-level deployments do not support complete mode.

    💡 Exam Trap: In incremental mode, if you redeploy a resource but omit a property, ARM resets that property to its default value. Incremental does not mean "partial update." The resource definition in the template always represents the full desired state.

    What-If Operation

    Before deploying, you can preview the changes ARM will make using the what-if operation. This shows which resources will be created, deleted, modified, or left unchanged.

    az deployment group what-if \
     --resource-group myResourceGroup \
     --template-file azuredeploy.json \
     --mode Complete
    
    New-AzResourceGroupDeployment `
     -ResourceGroupName myResourceGroup `
     -TemplateFile azuredeploy.json `
     -Mode Complete `
     -WhatIf
    

    Bicep: A Better Authoring Experience

    Bicep is a domain-specific language (DSL) created by Microsoft as a transparent abstraction over ARM template JSON. Every Bicep file is transpiled (compiled) into a standard ARM JSON template before deployment. Bicep is not a separate deployment mechanism; it produces ARM templates. This means Bicep supports every resource type and every API version that ARM templates support, from day one.

    Why Bicep Over JSON

    Bicep offers several advantages over raw JSON ARM templates:

    • Simpler, more readable syntax (roughly half the line count of equivalent JSON).
    • No need to manage dependsOn in most cases; Bicep automatically detects implicit dependencies when one resource references another's properties.
    • First-class support for modules, enabling code reuse across files and registries.
    • Native integration with Visual Studio Code via the Bicep extension (IntelliSense, validation, linting).
    • Parameters, variables, and outputs can be declared anywhere in the file (JSON requires them in fixed sections).

    Bicep File Structure

    A Bicep file uses the .bicep extension. There is no fixed section order.

    // Parameters
    param location string = resourceGroup().location
    param storageAccountName string
    
    // Resource declaration
    resource stg 'Microsoft.Storage/storageAccounts@2023-01-01' = {
     name: storageAccountName
     location: location
     sku: {
     name: 'Standard_LRS'
     }
     kind: 'StorageV2'
     properties: {}
    }
    
    // Output
    output blobEndpoint string = stg.properties.primaryEndpoints.blob
    

    In this example, stg is a symbolic name used only within the Bicep file to reference the resource. It does not appear in the deployed ARM template.

    Bicep Modules

    Modules let you break a large deployment into reusable pieces. A module is a separate .bicep file invoked with the module keyword.

    // main.bicep
    module storageModule 'modules/storage.bicep' = {
     name: 'storageDeployment'
     params: {
     storageAccountName: 'mystorageacct'
     location: location
     }
    }
    
    output storageId string = storageModule.outputs.storageId
    
    // modules/storage.bicep
    param storageAccountName string
    param location string
    
    resource stg 'Microsoft.Storage/storageAccounts@2023-01-01' = {
     name: storageAccountName
     location: location
     sku: {
     name: 'Standard_LRS'
     }
     kind: 'StorageV2'
     properties: {}
    }
    
    output storageId string = stg.id
    

    Modules can be published to a Bicep registry (backed by Azure Container Registry) or consumed as template specs for organizational sharing.

    Deploying Bicep

    Bicep files are deployed with the same commands as ARM templates. The CLI and PowerShell automatically compile the Bicep to JSON before sending it to ARM.

    az deployment group create \
     --resource-group myResourceGroup \
     --template-file main.bicep \
     --parameters storageAccountName=myuniquestorage01
    
    New-AzResourceGroupDeployment `
     -ResourceGroupName myResourceGroup `
     -TemplateFile main.bicep `
     -storageAccountName myuniquestorage01
    

    Decompiling JSON to Bicep

    You can convert existing ARM JSON templates to Bicep:

    az bicep decompile --file azuredeploy.json
    

    This produces a .bicep file. The decompiler handles most constructs but may leave warnings for hardcoded values, redundant dependencies, or expressions that cannot be cleanly translated.

    Template Specs

    A template spec is an Azure resource (Microsoft.Resources/templateSpecs) that stores an ARM template (or Bicep-compiled JSON) for later deployment. Template specs are version-controlled, shared via Azure RBAC, and can be deployed by anyone with the Template Spec Reader role without needing read access to the underlying template source. The maximum size of a template spec is approximately 2 MB.

    Deployment Stacks

    A deployment stack is a resource that manages a collection of Azure resources as a single unit. When you update or delete the stack, ARM can automatically clean up orphaned resources. Deployment stacks are replacing Azure Blueprints (which is being deprecated) and provide a cleaner alternative to complete mode for managing resource lifecycle. Unlike complete mode, deployment stacks can span multiple resource groups and even subscriptions.

    Exporting Existing Resources as Templates

    You can reverse-engineer existing resources into ARM templates via the portal (Resource Group > Export template), CLI, or PowerShell. Exported templates capture the resource's properties but often need cleanup: hardcoded names should become parameters, API versions may need updating, and unnecessary read-only properties should be removed.

    Decision Flow: ARM JSON vs. Bicep

    With deployment automation established, the next step is to understand the compute resources you will most commonly deploy: virtual machines.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the Microsoft - AZ-104 learning hub.