DevOps help for Cloud Platform Engineers
  • Welcome!
  • Quick Start Guide
  • About Me
  • CV
  • 🧠DevOps & SRE Foundations
    • DevOps Overview
      • Engineering Fundamentals
      • Implementing DevOps Strategy
      • DevOps Readiness Assessment
      • Lifecycle Management
      • The 12 Factor App
      • Design for Self Healing
      • Incident Management Best Practices (2025)
    • SRE Fundamentals
      • Toil Reduction
      • System Simplicity
      • Real-world Scenarios
        • AWS VM Log Monitoring API
    • Agile Development
      • Team Agreements
        • Definition of Done
        • Definition of Ready
        • Team Manifesto
        • Working Agreement
    • Industry Scenarios
      • Finance and Banking
      • Public Sector (UK/EU)
      • Energy Sector Edge Computing
  • DevOps Practices
    • Platform Engineering
    • FinOps
    • Observability
      • Modern Practices
  • 🚀Modern DevOps Practices
    • Infrastructure Testing
    • Modern Development
    • Database DevOps
  • 🛠️Infrastructure as Code (IaC)
    • Terraform
      • Getting Started - Installation and initial setup [BEGINNER]
      • Cloud Integrations - Provider-specific implementations
        • Azure Scenarios
        • AWS Scenarios
        • GCP Scenarios
      • Testing and Validation - Ensuring infrastructure quality
        • Unit Testing
        • Integration Testing
        • End-to-End Testing
        • Terratest Guide
      • Best Practices - Production-ready implementation strategies
        • State Management
        • Security
        • Code Organization
        • Performance
      • Tools & Utilities - Enhancing the Terraform workflow
        • Terraform Docs
        • TFLint
        • Checkov
        • Terrascan
      • CI/CD Integration - Automating infrastructure deployment
        • GitHub Actions - GitHub-based automation workflows
        • Azure Pipelines - Azure DevOps integration
        • GitLab CI - GitLab-based deployment pipelines
    • Bicep
      • Getting Started - First steps with Bicep [BEGINNER]
      • Template Specs
      • Best Practices - Guidelines for effective Bicep implementations
      • Modules - Building reusable components [INTERMEDIATE]
      • Examples - Sample implementations for common scenarios
      • Advanced Features
      • CI/CD Integration - Automating Bicep deployments
        • GitHub Actions
        • Azure Pipelines
  • 💰Cost Management & FinOps
    • Cloud Cost Optimization
  • 🐳Containers & Orchestration
    • Containerization Overview
    • Docker
      • Dockerfile Best Practices
      • Docker Compose
    • Kubernetes
      • CLI Tools - Essential command-line utilities
        • Kubectl
        • Kubens
        • Kubectx
      • Core Concepts
      • Components
      • Best Practices
        • Pod Security
        • Security Monitoring
        • Resource Limits
      • Advanced Features - Beyond the basics [ADVANCED]
        • Service Mesh
        • Ingress Controllers
          • NGINX
          • Traefik
          • Kong
          • Gloo Edge
      • Troubleshooting - Diagnosing and resolving common issues
        • Pod Troubleshooting Commands
      • Enterprise Architecture
      • Health Management
      • Security & Compliance
      • Virtual Clusters
    • OpenShift
  • Service Mesh & Networking
    • Service Mesh Implementation
  • Architecture Patterns
    • Data Mesh
    • Multi-Cloud Networking
    • Disaster Recovery
    • Chaos Engineering
  • Edge Computing
    • Implementation Guide
    • Serverless Edge
    • IoT Edge Patterns
    • Real-Time Processing
    • Edge AI/ML
    • Security Hardening
    • Observability Patterns
    • Network Optimization
    • Storage Patterns
  • 🔄CI/CD & GitOps
    • CI/CD Overview
    • Continuous Integration
    • Continuous Delivery
      • Deployment Strategies
      • Secrets Management
      • Blue-Green Deployments
      • Deployment Metrics
      • Progressive Delivery
      • Release Management for DevOps/SRE (2025)
    • CI/CD Platforms - Tool selection and implementation
      • Azure DevOps
        • Pipelines
          • Stages
          • Jobs
          • Steps
          • Templates - Reusable pipeline components
          • Extends
          • Service Connections - External service authentication
          • Best Practices for 2025
          • Agents and Runners
          • Third-Party Integrations
          • Azure DevOps CLI
        • Boards & Work Items
      • GitHub Actions
      • GitLab
        • GitLab Runner
        • Real-life scenarios
        • Installation guides
        • Pros and Cons
        • Comparison with alternatives
    • GitOps
      • Modern GitOps Practices
      • GitOps Patterns for Multi-Cloud (2025)
      • Flux
        • Overview
        • Progressive Delivery
        • Use GitOps with Flux, GitHub and AKS
  • Source Control
    • Source Control Overview
    • Git Branching Strategies
    • Component Versioning
    • Kubernetes Manifest Versioning
    • GitLab
    • Creating a Fork
    • Naming Branches
    • Pull Requests
    • Integrating LLMs into Source Control Workflows
  • ☁️Cloud Platforms
    • Cloud Strategy
    • Azure
      • Best Practices
      • Landing Zones
      • Services
      • Monitoring
      • Administration Tools - Platform management interfaces
        • Azure PowerShell
        • Azure CLI
      • Tips & Tricks
    • AWS
      • Authentication
      • Best Practices
      • Tips & Tricks
    • Google Cloud
      • Services
    • Private Cloud
  • 🔐Security & Compliance
    • DevSecOps Overview
    • DevSecOps Pipeline Security
    • DevSecOps
      • Real-life Examples
      • Scanning & Protection - Automated security tooling
        • Dependency Scanning
        • Credential Scanning
        • Container Security Scanning
        • Static Code Analysis
          • Best Practices
          • Tool Integration Guide
          • Pipeline Configuration
      • CI/CD Security
      • Secrets Rotation
    • Supply Chain Security
      • SLSA Framework
      • Binary Authorization
      • Artifact Signing
    • Security Best Practices
      • Threat Modeling
      • Kubernetes Security
    • SecOps
    • Zero Trust Model
    • Cloud Compliance
      • ISO/IEC 27001:2022
      • ISO 22301:2019
      • PCI DSS
      • CSA STAR
    • Security Frameworks
    • SIEM and SOAR
  • Security Architecture
    • Zero Trust Implementation
      • Identity Management
      • Network Security
      • Access Control
  • 🔍Observability & Monitoring
    • Observability Fundamentals
    • Logging
    • Metrics
    • Tracing
    • Dashboards
    • SLOs and SLAs
    • Observability as Code
    • Pipeline Observability
  • 🧪Testing Strategies
    • Testing Overview
    • Modern Testing Approaches
    • End-to-End Testing
    • Unit Testing
    • Performance Testing
      • Load Testing
    • Fault Injection Testing
    • Integration Testing
    • Smoke Testing
  • 🤖AI Integration
    • AIops Overview
      • Workflow Automation
      • Predictive Analytics
      • Code Quality
  • 🧠AI & LLM Integration
    • Overview
    • Claude
      • Installation Guide
      • Project Guides
      • MCP Server Setup
      • LLM Comparison
    • Ollama
      • Installation Guide
      • Configuration
      • Models and Fine-tuning
      • DevOps Usage
      • Docker Setup
      • GPU Setup
      • Open WebUI
    • Copilot
      • Installation Guide
      • VS Code Integration
      • CLI Usage
    • Gemini
      • Installation Guides - Platform-specific setup
        • Linux Installation
        • WSL Installation
        • NixOS Installation
      • Gemini 2.5 Features
      • Roles and Agents
      • NotebookML Guide
      • Cloud Infrastructure Deployment
      • Summary
  • 💻Development Environment
    • Tools Overview
    • DevOps Tools
    • Operating Systems - Development platforms
      • NixOS
        • Installation
        • Nix Language Guide
        • DevEnv with Nix
        • Cloud Deployments
      • WSL2
        • Distributions
        • Terminal Setup
    • Editor Environments
    • CLI Tools
      • Azure CLI
      • PowerShell
      • Linux Commands
      • YAML Tools
  • 📚Programming Languages
    • Python
    • Go
    • JavaScript/TypeScript
    • Java
    • Rust
  • 📖Documentation Best Practices
    • Documentation Strategy
    • Project Documentation
    • Release Notes
    • Static Sites
    • Documentation Templates
    • Real-World Examples
  • 📋Reference Materials
    • Glossary
    • Tool Comparison
    • Recommended Reading
    • Troubleshooting Guide
  • Platform Engineering
    • Implementation Guide
  • FinOps
    • Implementation Guide
  • AIOps
    • LLMOps Guide
  • Development Setup
    • Development Setup
Powered by GitBook
On this page
  • Basic PowerShell Deployment Script Example
  • Bash Script Example
  • Deployment Script Properties
  • Essential Properties
  • Identity Configuration
  • Passing Data To and From Scripts
  • Input Methods
  • Output Methods
  • Practical Examples
  • Example 1: Configure Azure RBAC
  • Example 2: Health Check and Validation
  • Best Practices
  • 1. Make Scripts Idempotent
  • 2. Implement Error Handling
  • 3. Minimize Script Duration
  • 4. Secure Secret Handling
  • 5. Use Managed Identities
  • Deployment Script Lifecycle
  • Troubleshooting Deployment Scripts
  • 1. View Script Logs
  • 2. Access Container Logs
  • 3. Common Issues and Solutions
  • Additional Resources
Edit on GitHub
  1. Infrastructure as Code (IaC)
  2. Bicep

Advanced Features

Deployment scripts in Bicep allow you to execute custom scripts during deployment to fill gaps in native resource provider capabilities and handle complex automation tasks.

Deployment scripts enable you to execute PowerShell or Bash scripts as part of your Azure deployments. This capability bridges the gap between declarative infrastructure definitions and imperative configuration tasks that would otherwise require manual intervention after deployment.

Basic PowerShell Deployment Script Example

The following example demonstrates a simple PowerShell deployment script that accepts a parameter and returns an output:

param name string = '\\"John Dole\\"'
param utcValue string = utcNow()
param location string = resourceGroup().location

resource runPowerShellInlineWithOutput 'Microsoft.Resources/deploymentScripts@2020-10-01' = {
  name: 'runPowerShellInlineWithOutput'
  location: location
  kind: 'AzurePowerShell'
  properties: {
    forceUpdateTag: utcValue
    azPowerShellVersion: '8.3'
    scriptContent: '''
      param([string] $name)
      $output = "Hello {0}" -f $name
      Write-Output $output
      $DeploymentScriptOutputs = @{}
      $DeploymentScriptOutputs["text"] = $output
    '''
    arguments: '-name ${name}'
    timeout: 'PT1H'
    cleanupPreference: 'OnSuccess'
    retentionInterval: 'P1D'
  }
}

output result string = runPowerShellInlineWithOutput.properties.outputs.text

Save the content into a Bicep file called inlineScript.bicep, and use the following PowerShell script to deploy:

$resourceGroupName = Read-Host -Prompt "Enter the name of the resource group to be created"
$location = Read-Host -Prompt "Enter the location (i.e. centralus)"

New-AzResourceGroup -Name $resourceGroupName -Location $location

New-AzResourceGroupDeployment -ResourceGroupName $resourceGroupName -TemplateFile "inlineScript.bicep"

Write-Host "Press [ENTER] to continue ..."

Bash Script Example

You can also use Bash scripts with the Azure CLI:

param location string = resourceGroup().location
param timestamp string = utcNow()

resource bashScript 'Microsoft.Resources/deploymentScripts@2020-10-01' = {
  name: 'create-storage-container'
  location: location
  kind: 'AzureCLI'
  identity: {
    type: 'UserAssigned'
    userAssignedIdentities: {
      '/subscriptions/{subscription-id}/resourceGroups/{resource-group}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identity-name}': {}
    }
  }
  properties: {
    forceUpdateTag: timestamp
    azCliVersion: '2.45.0'
    scriptContent: '''
      #!/bin/bash
      
      # Create storage account
      az storage account create \
        --name $STORAGE_ACCOUNT_NAME \
        --resource-group $RESOURCE_GROUP \
        --location $LOCATION \
        --sku Standard_LRS
      
      # Create container
      az storage container create \
        --name $CONTAINER_NAME \
        --account-name $STORAGE_ACCOUNT_NAME \
        --auth-mode login
      
      # Set output
      echo "{ \"storageAccount\": \"$STORAGE_ACCOUNT_NAME\", \"container\": \"$CONTAINER_NAME\" }" > $AZ_SCRIPTS_OUTPUT_PATH
    '''
    environmentVariables: [
      {
        name: 'STORAGE_ACCOUNT_NAME'
        value: 'storage${uniqueString(resourceGroup().id)}'
      }
      {
        name: 'CONTAINER_NAME'
        value: 'content'
      }
      {
        name: 'RESOURCE_GROUP'
        value: resourceGroup().name
      }
      {
        name: 'LOCATION'
        value: location
      }
    ]
    timeout: 'PT30M'
    cleanupPreference: 'OnSuccess'
    retentionInterval: 'P1D'
  }
}

output storageAccountName string = contains(bashScript.properties.outputs, 'storageAccount') ? bashScript.properties.outputs.storageAccount : ''
output containerName string = contains(bashScript.properties.outputs, 'container') ? bashScript.properties.outputs.container : ''

Deployment Script Properties

Essential Properties

Property
Description

kind

Specifies the script type - AzurePowerShell or AzureCLI

azPowerShellVersion

Version of PowerShell to use (e.g., '8.3')

azCliVersion

Version of Azure CLI to use (e.g., '2.45.0')

scriptContent

The script to execute during deployment

timeout

Maximum allowed script execution time in ISO 8601 format (e.g., 'PT1H' for 1 hour)

retentionInterval

How long to retain script resources in ISO 8601 format (e.g., 'P1D' for 1 day)

cleanupPreference

When to clean up deployment resources: 'Always', 'OnSuccess', or 'OnExpiration'

Identity Configuration

Deployment scripts require an identity to execute. You can use either:

  1. User-assigned managed identity (recommended for production):

identity: {
  type: 'UserAssigned'
  userAssignedIdentities: {
    '/subscriptions/{sub-id}/resourceGroups/{rg}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identity-name}': {}
  }
}
  1. System-assigned managed identity (simpler but less flexible):

identity: {
  type: 'SystemAssigned'
}

Passing Data To and From Scripts

Input Methods

  1. Script Arguments

arguments: '-name ${name} -environment ${environment}'
  1. Environment Variables

environmentVariables: [
  {
    name: 'STORAGE_NAME'
    value: storageName
  }
  {
    name: 'SECRET_VALUE'
    secureValue: secretValue  // For sensitive values
  }
]

Output Methods

  1. Using $DeploymentScriptOutputs in PowerShell

$DeploymentScriptOutputs = @{}
$DeploymentScriptOutputs["key1"] = "value1"
$DeploymentScriptOutputs["key2"] = "value2"
  1. Using $AZ_SCRIPTS_OUTPUT_PATH in Bash

echo '{"key1": "value1", "key2": "value2"}' > $AZ_SCRIPTS_OUTPUT_PATH
  1. Accessing Outputs in Bicep

output result1 string = deploymentScript.properties.outputs.key1
output result2 string = deploymentScript.properties.outputs.key2

Practical Examples

Example 1: Configure Azure RBAC

param principalId string
param roleDefinitionId string
param timestamp string = utcNow()
param location string = resourceGroup().location

resource configureRbac 'Microsoft.Resources/deploymentScripts@2020-10-01' = {
  name: 'assign-rbac-role'
  location: location
  kind: 'AzurePowerShell'
  identity: {
    type: 'UserAssigned'
    userAssignedIdentities: {
      '${userManagedIdentity.id}': {}
    }
  }
  properties: {
    forceUpdateTag: timestamp
    azPowerShellVersion: '8.3'
    scriptContent: '''
      param(
        [string] $PrincipalId,
        [string] $RoleDefinitionId,
        [string] $Scope
      )

      # Check if role assignment exists
      $existing = Get-AzRoleAssignment -ObjectId $PrincipalId -RoleDefinitionId $RoleDefinitionId -Scope $Scope -ErrorAction SilentlyContinue
      
      if (-not $existing) {
        # Create the role assignment
        $result = New-AzRoleAssignment -ObjectId $PrincipalId -RoleDefinitionId $RoleDefinitionId -Scope $Scope
        $DeploymentScriptOutputs = @{
          'assignmentId' = $result.RoleAssignmentId
          'principalId' = $result.ObjectId
          'roleDefinitionId' = $result.RoleDefinitionId
        }
        Write-Output "Created new role assignment: $($result.RoleAssignmentId)"
      } else {
        $DeploymentScriptOutputs = @{
          'assignmentId' = $existing.RoleAssignmentId
          'principalId' = $existing.ObjectId
          'roleDefinitionId' = $existing.RoleDefinitionId
          'status' = 'AlreadyExists'
        }
        Write-Output "Role assignment already exists: $($existing.RoleAssignmentId)"
      }
    '''
    arguments: '-PrincipalId ${principalId} -RoleDefinitionId ${roleDefinitionId} -Scope ${resourceGroup().id}'
    timeout: 'PT30M'
    cleanupPreference: 'OnSuccess'
    retentionInterval: 'P1D'
  }
}

resource userManagedIdentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2018-11-30' existing = {
  name: 'deployment-identity'
}

output rbacAssignmentId string = configureRbac.properties.outputs.assignmentId

Example 2: Health Check and Validation

param webAppName string
param location string = resourceGroup().location

resource healthCheck 'Microsoft.Resources/deploymentScripts@2020-10-01' = {
  name: 'webapp-health-check'
  location: location
  kind: 'AzureCLI'
  identity: {
    type: 'SystemAssigned'
  }
  properties: {
    forceUpdateTag: utcNow()
    azCliVersion: '2.45.0'
    scriptContent: '''
      #!/bin/bash
      
      # Get the web app URL
      WEBAPP_URL="https://$WEBAPP_NAME.azurewebsites.net/health"
      
      echo "Checking health endpoint at $WEBAPP_URL"
      
      # Wait for the web app to be responsive (max 2 minutes)
      for i in {1..12}; do
        STATUS_CODE=$(curl -s -o /dev/null -w "%{http_code}" $WEBAPP_URL)
        
        if [ $STATUS_CODE -eq 200 ]; then
          echo "Health check passed with status code: $STATUS_CODE"
          echo "{ \"status\": \"Healthy\", \"statusCode\": \"$STATUS_CODE\" }" > $AZ_SCRIPTS_OUTPUT_PATH
          exit 0
        else
          echo "Attempt $i: Health check returned status code: $STATUS_CODE, retrying in 10 seconds..."
          sleep 10
        fi
      done
      
      echo "Health check failed after multiple attempts"
      echo "{ \"status\": \"Unhealthy\", \"statusCode\": \"$STATUS_CODE\" }" > $AZ_SCRIPTS_OUTPUT_PATH
      exit 1
    '''
    environmentVariables: [
      {
        name: 'WEBAPP_NAME'
        value: webAppName
      }
    ]
    timeout: 'PT5M'
    cleanupPreference: 'OnSuccess'
    retentionInterval: 'P1D'
  }
}

output healthStatus string = healthCheck.properties.outputs.status
output statusCode string = healthCheck.properties.outputs.statusCode

Best Practices

1. Make Scripts Idempotent

Design your scripts to be safely rerunnable without causing side effects:

# Check if resource exists before creating
if (-not (Get-AzStorageAccount -ResourceGroupName $ResourceGroup -Name $StorageName -ErrorAction SilentlyContinue)) {
    New-AzStorageAccount -ResourceGroupName $ResourceGroup -Name $StorageName -Location $Location -SkuName Standard_LRS
    Write-Output "Storage account created"
} else {
    Write-Output "Storage account already exists"
}

2. Implement Error Handling

Add error handling to your scripts to make troubleshooting easier:

try {
    # Your script logic here
    $result = Get-AzResource -Name $ResourceName
    $DeploymentScriptOutputs['status'] = 'Success'
} catch {
    $errorMessage = $_.Exception.Message
    Write-Error $errorMessage
    $DeploymentScriptOutputs['status'] = 'Failed'
    $DeploymentScriptOutputs['error'] = $errorMessage
    exit 1
}

3. Minimize Script Duration

Keep deployment scripts short and focused:

  1. Use async operations where possible

  2. Avoid polling loops with long intervals

  3. Consider breaking complex operations into multiple scripts

4. Secure Secret Handling

Never hardcode secrets in your deployment scripts:

// Use secureValue for sensitive information
environmentVariables: [
  {
    name: 'API_KEY'
    secureValue: apiKey  // apiKey should be a secure parameter
  }
]

5. Use Managed Identities

Prefer user-assigned managed identities with pre-configured permissions:

resource managedIdentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2018-11-30' = {
  name: 'script-identity'
  location: location
}

module assignRoles 'roles.bicep' = {
  name: 'assign-roles'
  params: {
    principalId: managedIdentity.properties.principalId
    roles: [
      'Reader',
      'Storage Blob Data Contributor'
    ]
  }
}

resource deploymentScript 'Microsoft.Resources/deploymentScripts@2020-10-01' = {
  name: 'configuration-script'
  location: location
  kind: 'AzurePowerShell'
  identity: {
    type: 'UserAssigned'
    userAssignedIdentities: {
      '${managedIdentity.id}': {}
    }
  }
  // ...other properties
}

Deployment Script Lifecycle

  1. Creation: Azure creates a container instance to run your script

  2. Execution: Your script runs with the specified identity and permissions

  3. Output Capture: Results are stored in the deployment script resource

  4. Cleanup: Container instance is deleted based on cleanupPreference

  5. Retention: Deployment script resource remains available according to retentionInterval

Troubleshooting Deployment Scripts

1. View Script Logs

# Get logs from deployment script
$logs = Get-AzDeploymentScriptLog -ResourceGroupName "myResourceGroup" -DeploymentScriptName "myScript"
$logs

2. Access Container Logs

If cleanupPreference is not set to Always, you can access the container logs:

# Get container logs
$containerLogs = Get-AzDeploymentScriptLog -ResourceGroupName "myResourceGroup" -DeploymentScriptName "myScript" -ContainerLog
$containerLogs

3. Common Issues and Solutions

Issue
Solution

Script timeout

Increase timeout value or optimize script

Permission errors

Verify managed identity has appropriate RBAC roles

Missing modules

Install required modules in script using Install-Module

Script execution errors

Use try/catch blocks and output detailed error messages

Additional Resources

PreviousExamples - Sample implementations for common scenariosNextCI/CD Integration - Automating Bicep deployments

Last updated 1 day ago

🛠️
Official Microsoft Deployment Scripts Documentation
Azure PowerShell Reference
Azure CLI Reference