How to save and deploy Azure alerts as code in Bicep

Bicep is the new kid on the block when it comes to IaC (Infrastructure as Code). It ties closely with ARM-templates. It's flexible and easier to use and read than ARM. Alerts can be hard to keep track of in a IaC setup. Let's try to create and deploy alerts right from the az cli with bicep!

First of all, we need to create an alert. I've decided that I want to monitor my database size. Let's start by creating an alert rule in the Azure portal.

Setting up alert in azure portal

Once the Alert is created, you should be able to find the alert in the Azure resource explorer. Simply search and you should be able to see the JSON for the alert resource.

JSON for the alert resource

To download the full ARM-template, click open blade, export template and, Download. Create a bicep file with az bicep decompile: az bicep decompile --file databaseGettingFull.json.

After decompiling, I want to make the script run for multiple databases and multiple action groups. After some modifications, my script should look like this.

var databases = [

var sqlserver_externalid = '/subscriptions/subscription-guid/resourceGroups/atlas-prod-rg/providers/Microsoft.Sql/servers/my-sqlserver'
var actiongroups = [

resource metricAlerts_database_is_getting_full_resource 'microsoft.insights/metricAlerts@2018-03-01' = [ for database in databases: {
  name: '${database} database is getting full'
  location: 'global'
  properties: {
    description: '${database} database on thon-atlas-prod-sqlserver is getting full (greater than 70%).\nConsider increasing storage'
    severity: 3
    enabled: true
    scopes: [
    evaluationFrequency: 'PT1H'
    windowSize: 'PT6H'
    criteria: {
      allOf: [
          threshold: 70
          name: 'Metric1'
          metricNamespace: 'Microsoft.Sql/servers/databases'
          metricName: 'storage_percent'
          operator: 'GreaterThan'
          timeAggregation: 'Maximum'
          criterionType: 'StaticThresholdCriterion'
      'odata.type': 'Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria'
    autoMitigate: true
    targetResourceType: 'Microsoft.Sql/servers/databases'
    targetResourceRegion: 'westeurope'
    actions: [ for actiongroups_id in actiongroups: {
      actionGroupId: actiongroups_id
      webHookProperties: {}

Now simply deploy with az cli: az deployment group create --template-file databaseGettingFull.bicep --resource-group my-alerts-prod-rg. Now we deploy a list of alerts and we no longer need to manually modify the alerts in the portal.