Bylaw

Gallery › Security Center › Azure built-in policies

Deploy Workflow Automation for Microsoft Defender for Cloud recommendations

Uses Condition Policy DeployIfNotExists Mode All Version 5.0.1

Enable automation of Microsoft Defender for Cloud recommendations. This policy deploys a workflow automation with your conditions and triggers on the assigned scope. To deploy this policy on newly created subscriptions, open the Compliance tab, select the relevant non-compliant assignment and create a remediation task.

ConvertTo-Bylaw converted this policy, and proved it compiles back to the same definition. Conditions the language can't express yet are written as raw JSON with Condition.

Azure Policy JSONASC_WorkflowAutomationASCRecommendations_DINE.json · 402 lines
{
  "properties": {
    "displayName": "Deploy Workflow Automation for Microsoft Defender for Cloud recommendations",
    "policyType": "BuiltIn",
    "mode": "All",
    "description": "Enable automation of Microsoft Defender for Cloud recommendations. This policy deploys a workflow automation with your conditions and triggers on the assigned scope. To deploy this policy on newly created subscriptions, open the Compliance tab, select the relevant non-compliant assignment and create a remediation task.",
    "metadata": {
      "version": "5.0.1",
      "category": "Security Center"
    },
    "version": "5.0.1",
    "parameters": {
      "automationName": {
        "type": "String",
        "metadata": {
          "displayName": "Automation name",
          "description": "This is the automation name."
        }
      },
      "resourceGroupName": {
        "type": "String",
        "metadata": {
          "displayName": "Resource group name",
          "description": "The resource group name where the workflow automation is created. If you enter a name for a resource group that doesn't exist, it'll be created in the subscription."
        }
      },
      "resourceGroupLocation": {
        "type": "String",
        "metadata": {
          "displayName": "Resource group location",
          "description": "The location where the resource group and the workflow automation are created.",
          "strongType": "location"
        }
      },
      "createResourceGroup": {
        "type": "Boolean",
        "metadata": {
          "displayName": "Create resource group",
          "description": "If a resource group does not exists in the scope, a new resource group will be created. If the resource group exists and this flag is set to 'true' the policy will re-deploy the resource group. Please note this will reset any Azure Tag on the resource group."
        },
        "allowedValues": [
          true,
          false
        ],
        "defaultValue": true
      },
      "recommendationNames": {
        "type": "Array",
        "metadata": {
          "displayName": "Recommendation IDs",
          "description": "For all recommendations, leave empty. For specific recommendations, enter a list of recommendation IDs separated by semicolons (';'). Recommendation IDs are available through the Assessments API (https://docs.microsoft.com/en-us/rest/api/securitycenter/assessments), or Azure Resource Graph Explorer, choose securityresources and microsoft.security/assessments."
        },
        "defaultValue": []
      },
      "recommendationSeverities": {
        "type": "Array",
        "metadata": {
          "displayName": "Recommendation severities",
          "description": "Determines recommendation severities. Example: High;Medium;Low;"
        },
        "allowedValues": [
          "High",
          "Medium",
          "Low"
        ],
        "defaultValue": [
          "High",
          "Medium",
          "Low"
        ]
      },
      "recommendationStates": {
        "type": "Array",
        "metadata": {
          "displayName": "Recommendation states",
          "description": "Determines recommendation states. Recommendations with unhealthy state require your attention to resolve. When a recommendation state is healthy, it no longer applies to the resource as Microsoft Defender for Cloud detects it as healthy. A recommendation is not-applicable if, for example, it was disabled in the Security Policy. Example: Healthy;Unhealthy;Not Applicable;"
        },
        "allowedValues": [
          "Healthy",
          "Unhealthy",
          "Not Applicable"
        ],
        "defaultValue": [
          "Healthy",
          "Unhealthy",
          "Not Applicable"
        ]
      },
      "logicAppResourceId": {
        "type": "String",
        "metadata": {
          "displayName": "Logic App",
          "description": "The Logic App that is triggered.",
          "strongType": "Microsoft.Logic/workflows",
          "assignPermissions": true
        }
      },
      "logicAppTrigger": {
        "type": "String",
        "metadata": {
          "displayName": "Logic app trigger",
          "description": "The trigger connector of the logic app that is triggered. Possible values: 'Manual (Incoming HTTP request)', 'When an Azure Security Center Recommendation is created or triggered'."
        },
        "allowedValues": [
          "Manual (Incoming HTTP request)",
          "When an Azure Security Center Recommendation is created or triggered"
        ]
      }
    },
    "policyRule": {
      "if": {
        "field": "type",
        "equals": "Microsoft.Resources/subscriptions"
      },
      "then": {
        "effect": "deployIfNotExists",
        "details": {
          "type": "Microsoft.Security/automations",
          "name": "[parameters('automationName')]",
          "existenceScope": "resourcegroup",
          "ResourceGroupName": "[parameters('resourceGroupName')]",
          "deploymentScope": "subscription",
          "roleDefinitionIds": [
            "/providers/microsoft.authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"
          ],
          "existenceCondition": {
            "allOf": [
              {
                "field": "Microsoft.Security/automations/isEnabled",
                "equals": true
              },
              {
                "field": "Microsoft.Security/automations/sources[*].ruleSets[*].rules[*].expectedValue",
                "in": "[union(if(equals(length(parameters('recommendationNames')),0),array('Microsoft.Security/assessments'),parameters('recommendationNames')),parameters('recommendationSeverities'),if(contains(parameters('recommendationStates'),'Not Applicable'),union(parameters('recommendationStates'), array('notapplicable')),parameters('recommendationStates')))]"
              },
              {
                "count": {
                  "value": "[parameters('recommendationSeverities')]",
                  "name": "recommendationSeverity",
                  "where": {
                    "count": {
                      "field": "Microsoft.Security/automations/sources[*].ruleSets[*].rules[*]",
                      "where": {
                        "allOf": [
                          {
                            "field": "Microsoft.Security/automations/sources[*].ruleSets[*].rules[*].propertyJPath",
                            "equals": "properties.metadata.severity"
                          },
                          {
                            "field": "Microsoft.Security/automations/sources[*].ruleSets[*].rules[*].expectedValue",
                            "equals": "[current('recommendationSeverity')]"
                          }
                        ]
                      }
                    },
                    "equals": "[mul(max(1,length(parameters('recommendationNames'))),length(parameters('recommendationStates')))]"
                  }
                },
                "equals": "[length(parameters('recommendationSeverities'))]"
              },
              {
                "count": {
                  "value": "[parameters('recommendationStates')]",
                  "name": "recommendationState",
                  "where": {
                    "count": {
                      "field": "Microsoft.Security/automations/sources[*].ruleSets[*].rules[*]",
                      "where": {
                        "allOf": [
                          {
                            "field": "Microsoft.Security/automations/sources[*].ruleSets[*].rules[*].propertyJPath",
                            "equals": "properties.status.code"
                          },
                          {
                            "field": "Microsoft.Security/automations/sources[*].ruleSets[*].rules[*].expectedValue",
                            "equals": "[replace(current('recommendationState'), ' ','')]"
                          }
                        ]
                      }
                    },
                    "equals": "[mul(max(1,length(parameters('recommendationNames'))),length(parameters('recommendationSeverities')))]"
                  }
                },
                "equals": "[length(parameters('recommendationStates'))]"
              },
              {
                "count": {
                  "value": "[parameters('recommendationNames')]",
                  "name": "recommendationName",
                  "where": {
                    "count": {
                      "field": "Microsoft.Security/automations/sources[*].ruleSets[*].rules[*]",
                      "where": {
                        "allOf": [
                          {
                            "field": "Microsoft.Security/automations/sources[*].ruleSets[*].rules[*].propertyJPath",
                            "equals": "name"
                          },
                          {
                            "field": "Microsoft.Security/automations/sources[*].ruleSets[*].rules[*].expectedValue",
                            "equals": "[current('recommendationName')]"
                          }
                        ]
                      }
                    },
                    "equals": "[mul(length(parameters('recommendationSeverities')),length(parameters('recommendationStates')))]"
                  }
                },
                "equals": "[length(parameters('recommendationNames'))]"
              }
            ]
          },
          "deployment": {
            "location": "westeurope",
            "properties": {
              "mode": "incremental",
              "template": {
                "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
                "contentVersion": "1.0.0.0",
                "parameters": {
                  "automationName": {
                    "type": "string"
                  },
                  "resourceGroupName": {
                    "type": "string"
                  },
                  "resourceGroupLocation": {
                    "type": "string"
                  },
                  "createResourceGroup": {
                    "type": "bool"
                  },
                  "recommendationNames": {
                    "type": "array"
                  },
                  "recommendationSeverities": {
                    "type": "array"
                  },
                  "recommendationStates": {
                    "type": "array"
                  },
                  "logicAppResourceId": {
                    "type": "string"
                  },
                  "logicAppTrigger": {
                    "type": "string"
                  },
                  "guidValue": {
                    "type": "string",
                    "defaultValue": "[newGuid()]"
                  }
                },
                "variables": {
                  "scopeDescription": "scope for subscription {0}",
                  "recommendationNamesLength": "[length(parameters('recommendationNames'))]",
                  "recommendationSeveritiesLength": "[length(parameters('recommendationSeverities'))]",
                  "recommendationStatesLength": "[length(parameters('recommendationStates'))]",
                  "recommendationNamesLengthIfEmpty": "[if(equals(variables('recommendationNamesLength'), 0), 1, variables('recommendationNamesLength'))]",
                  "recommendationSeveritiesLengthIfEmpty": "[if(equals(variables('recommendationSeveritiesLength'), 0), 1, variables('recommendationSeveritiesLength'))]",
                  "recommendationStatesLengthIfEmpty": "[if(equals(variables('recommendationStatesLength'), 0), 1, variables('recommendationStatesLength'))]",
                  "totalRuleCombinationsForOneRecommendationName": "[mul(variables('recommendationSeveritiesLengthIfEmpty'),variables('recommendationStatesLengthIfEmpty'))]",
                  "totalRuleCombinationsForOneRecommendationSeverity": "[variables('recommendationStatesLengthIfEmpty')]",
                  "totalRuleCombinationsForOneRecommendationState": 1,
                  "stateMap": {
                    "Healthy": "healthy",
                    "Unhealthy": "unhealthy",
                    "Not Applicable": "notapplicable"
                  },
                  "triggerMap": {
                    "Manual (Incoming HTTP request)": "manual",
                    "When an Azure Security Center Recommendation is created or triggered": "When_a_Microsoft_Defender_for_Cloud_recommendation_is_created_or_triggered"
                  }
                },
                "resources": [
                  {
                    "condition": "[parameters('createResourceGroup')]",
                    "name": "[parameters('resourceGroupName')]",
                    "type": "Microsoft.Resources/resourceGroups",
                    "apiVersion": "2019-10-01",
                    "location": "[parameters('resourceGroupLocation')]"
                  },
                  {
                    "type": "Microsoft.Resources/deployments",
                    "apiVersion": "2019-10-01",
                    "name": "[concat('nestedAutomationDeployment', '_', parameters('guidValue'))]",
                    "resourceGroup": "[parameters('resourceGroupName')]",
                    "dependsOn": [
                      "[resourceId('Microsoft.Resources/resourceGroups/', parameters('resourceGroupName'))]"
                    ],
                    "properties": {
                      "mode": "Incremental",
                      "template": {
                        "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                        "contentVersion": "1.0.0.0",
                        "parameters": {},
                        "variables": {},
                        "resources": [
                          {
                            "tags": {},
                            "apiVersion": "2019-01-01-preview",
                            "location": "[parameters('resourceGroupLocation')]",
                            "name": "[parameters('automationName')]",
                            "type": "Microsoft.Security/automations",
                            "dependsOn": [],
                            "properties": {
                              "description": "Workflow Automation for Microsoft Defender for Cloud recommendations via policy",
                              "isEnabled": true,
                              "scopes": [
                                {
                                  "description": "[replace(variables('scopeDescription'),'{0}', subscription().subscriptionId)]",
                                  "scopePath": "[subscription().id]"
                                }
                              ],
                              "sources": [
                                {
                                  "eventSource": "Assessments",
                                  "copy": [
                                    {
                                      "name": "ruleSets",
                                      "count": "[mul(variables('recommendationNamesLengthIfEmpty'), mul(variables('recommendationSeveritiesLengthIfEmpty'),variables('recommendationStatesLengthIfEmpty')))]",
                                      "input": {
                                        "rules": [
                                          {
                                            "propertyJPath": "[if(equals(variables('recommendationNamesLength'), 0), 'type', 'name')]",
                                            "propertyType": "string",
                                            "expectedValue": "[if(equals(variables('recommendationNamesLength'), 0), 'Microsoft.Security/assessments', parameters('recommendationNames')[mod(div(copyIndex('ruleSets'), variables('totalRuleCombinationsForOneRecommendationName')), variables('recommendationNamesLength'))])]",
                                            "operator": "Contains"
                                          },
                                          {
                                            "propertyJPath": "properties.metadata.severity",
                                            "propertyType": "string",
                                            "expectedValue": "[parameters('recommendationSeverities')[mod(div(copyIndex('ruleSets'), variables('totalRuleCombinationsForOneRecommendationSeverity')), variables('recommendationSeveritiesLength'))]]",
                                            "operator": "Equals"
                                          },
                                          {
                                            "propertyJPath": "properties.status.code",
                                            "propertyType": "string",
                                            "expectedValue": "[variables('stateMap')[parameters('recommendationStates')[mod(div(copyIndex('ruleSets'), variables('totalRuleCombinationsForOneRecommendationState')), variables('recommendationStatesLength'))]]]",
                                            "operator": "Contains"
                                          }
                                        ]
                                      }
                                    }
                                  ]
                                }
                              ],
                              "actions": [
                                {
                                  "actionType": "LogicApp",
                                  "logicAppResourceId": "[parameters('logicAppResourceId')]",
                                  "uri": "[listCallbackUrl(concat(parameters('logicAppResourceId'), '/triggers/', variables('triggerMap')[parameters('logicAppTrigger')]),'2016-06-01').value]"
                                }
                              ]
                            }
                          }
                        ]
                      }
                    }
                  }
                ]
              },
              "parameters": {
                "automationName": {
                  "value": "[parameters('automationName')]"
                },
                "resourceGroupName": {
                  "value": "[parameters('resourceGroupName')]"
                },
                "resourceGroupLocation": {
                  "value": "[parameters('resourceGroupLocation')]"
                },
                "createResourceGroup": {
                  "value": "[parameters('createResourceGroup')]"
                },
                "recommendationNames": {
                  "value": "[parameters('recommendationNames')]"
                },
                "recommendationSeverities": {
                  "value": "[parameters('recommendationSeverities')]"
                },
                "recommendationStates": {
                  "value": "[parameters('recommendationStates')]"
                },
                "logicAppResourceId": {
                  "value": "[parameters('logicAppResourceId')]"
                },
                "logicAppTrigger": {
                  "value": "[parameters('logicAppTrigger')]"
                }
              }
            }
          }
        }
      }
    },
    "versions": [
      "5.0.1"
    ]
  },
  "id": "/providers/Microsoft.Authorization/policyDefinitions/73d6ab6c-2475-4850-afd6-43795f3492ef",
  "name": "73d6ab6c-2475-4850-afd6-43795f3492ef"
}
Bylaw73d6ab6c-2475-4850-afd6-43795f3492ef.bylaw.ps1 · 111 lines
# Converted from ASC_WorkflowAutomationASCRecommendations_DINE.json by ConvertTo-Bylaw.
Policy '73d6ab6c-2475-4850-afd6-43795f3492ef' {

    Properties @{
        DisplayName   = 'Deploy Workflow Automation for Microsoft Defender for Cloud recommendations'
        Description   = 'Enable automation of Microsoft Defender for Cloud recommendations. This policy deploys a workflow automation with your conditions and triggers on the assigned scope. To deploy this policy on newly created subscriptions, open the Compliance tab, select the relevant non-compliant assignment and create a remediation task.'
        Version       = '5.0.1'
        Category      = 'Security Center'
        PolicyVersion = '5.0.1'
        Mode          = 'All'
    }

    Parameter AutomationName @{
        Type        = 'String'
        DisplayName = 'Automation name'
        Description = 'This is the automation name.'
    }
    Parameter ResourceGroupName @{
        Type        = 'String'
        DisplayName = 'Resource group name'
        Description = 'The resource group name where the workflow automation is created. If you enter a name for a resource group that doesn''t exist, it''ll be created in the subscription.'
    }
    Parameter ResourceGroupLocation @{
        Type        = 'String'
        DisplayName = 'Resource group location'
        Description = 'The location where the resource group and the workflow automation are created.'
        Metadata    = [ordered]@{ strongType = 'location' }
    }
    Parameter CreateResourceGroup @{
        Type          = 'Boolean'
        AllowedValues = @($true, $false)
        Default       = $true
        DisplayName   = 'Create resource group'
        Description   = 'If a resource group does not exists in the scope, a new resource group will be created. If the resource group exists and this flag is set to ''true'' the policy will re-deploy the resource group. Please note this will reset any Azure Tag on the resource group.'
    }
    Parameter RecommendationNames @{
        Type        = 'Array'
        Default     = @()
        DisplayName = 'Recommendation IDs'
        Description = 'For all recommendations, leave empty. For specific recommendations, enter a list of recommendation IDs separated by semicolons ('';''). Recommendation IDs are available through the Assessments API (https://docs.microsoft.com/en-us/rest/api/securitycenter/assessments), or Azure Resource Graph Explorer, choose securityresources and microsoft.security/assessments.'
    }
    Parameter RecommendationSeverities @{
        Type          = 'Array'
        AllowedValues = @('High', 'Medium', 'Low')
        Default       = @('High', 'Medium', 'Low')
        DisplayName   = 'Recommendation severities'
        Description   = 'Determines recommendation severities. Example: High;Medium;Low;'
    }
    Parameter RecommendationStates @{
        Type          = 'Array'
        AllowedValues = @('Healthy', 'Unhealthy', 'Not Applicable')
        Default       = @('Healthy', 'Unhealthy', 'Not Applicable')
        DisplayName   = 'Recommendation states'
        Description   = 'Determines recommendation states. Recommendations with unhealthy state require your attention to resolve. When a recommendation state is healthy, it no longer applies to the resource as Microsoft Defender for Cloud detects it as healthy. A recommendation is not-applicable if, for example, it was disabled in the Security Policy. Example: Healthy;Unhealthy;Not Applicable;'
    }
    Parameter LogicAppResourceId @{
        Type        = 'String'
        DisplayName = 'Logic App'
        Description = 'The Logic App that is triggered.'
        Metadata    = [ordered]@{ strongType = 'Microsoft.Logic/workflows'; assignPermissions = $true }
    }
    Parameter LogicAppTrigger @{
        Type          = 'String'
        AllowedValues = @('Manual (Incoming HTTP request)', 'When an Azure Security Center Recommendation is created or triggered')
        DisplayName   = 'Logic app trigger'
        Description   = 'The trigger connector of the logic app that is triggered. Possible values: ''Manual (Incoming HTTP request)'', ''When an Azure Security Center Recommendation is created or triggered''.'
    }

    Resource 'Microsoft.Resources/subscriptions'

    DeployIfNotExists 'Microsoft.Security/automations' -Role 'Contributor' -Name (Param AutomationName) -ResourceGroupName (Param ResourceGroupName) -ExistenceScope ResourceGroup {
        Require 'isEnabled, sources, ruleSets and 5 more are as required' {
            Field isEnabled | Must -Be $true
            Field sources | Must -Exist
            Each 'sources[*]' {
                Field ruleSets | Must -Exist
                Each 'ruleSets[*]' {
                    Field rules | Must -Exist
                    Each 'rules[*]' {
                        Field expectedValue | Must -BeIn (Arm '[union(if(equals(length(parameters(''recommendationNames'')),0),array(''Microsoft.Security/assessments''),parameters(''recommendationNames'')),parameters(''recommendationSeverities''),if(contains(parameters(''recommendationStates''),''Not Applicable''),union(parameters(''recommendationStates''), array(''notapplicable'')),parameters(''recommendationStates'')))]') -Strict
                    }
                }
            }
            Count -Value (Param RecommendationSeverities) -Name recommendationSeverity -Where {
                Condition '{ "count": { "field": "Microsoft.Security/automations/sources[*].ruleSets[*].rules[*]", "where": { "allOf": [ { "field": "Microsoft.Security/automations/sources[*].ruleSets[*].rules[*].propertyJPath", "equals": "properties.metadata.severity" }, { "field": "Microsoft.Security/automations/sources[*].ruleSets[*].rules[*].expectedValue", "equals": "[current(''recommendationSeverity'')]" } ] } }, "equals": "[mul(max(1,length(parameters(''recommendationNames''))),length(parameters(''recommendationStates'')))]" }'
            } | Must -Be (Param RecommendationSeverities -Length)
            Count -Value (Param RecommendationStates) -Name recommendationState -Where {
                Condition '{ "count": { "field": "Microsoft.Security/automations/sources[*].ruleSets[*].rules[*]", "where": { "allOf": [ { "field": "Microsoft.Security/automations/sources[*].ruleSets[*].rules[*].propertyJPath", "equals": "properties.status.code" }, { "field": "Microsoft.Security/automations/sources[*].ruleSets[*].rules[*].expectedValue", "equals": "[replace(current(''recommendationState''), '' '','''')]" } ] } }, "equals": "[mul(max(1,length(parameters(''recommendationNames''))),length(parameters(''recommendationSeverities'')))]" }'
            } | Must -Be (Param RecommendationStates -Length)
            Count -Value (Param RecommendationNames) -Name recommendationName -Where {
                Condition '{ "count": { "field": "Microsoft.Security/automations/sources[*].ruleSets[*].rules[*]", "where": { "allOf": [ { "field": "Microsoft.Security/automations/sources[*].ruleSets[*].rules[*].propertyJPath", "equals": "name" }, { "field": "Microsoft.Security/automations/sources[*].ruleSets[*].rules[*].expectedValue", "equals": "[current(''recommendationName'')]" } ] } }, "equals": "[mul(length(parameters(''recommendationSeverities'')),length(parameters(''recommendationStates'')))]" }'
            } | Must -Be (Param RecommendationNames -Length)
        }
        Deployment @{
            TemplateFile = './templates/73d6ab6c-2475-4850-afd6-43795f3492ef.json'
            Scope        = 'Subscription'
            Location     = 'westeurope'
            Parameters   = [ordered]@{
                automationName           = (Param AutomationName)
                resourceGroupName        = (Param ResourceGroupName)
                resourceGroupLocation    = (Param ResourceGroupLocation)
                createResourceGroup      = (Param CreateResourceGroup)
                recommendationNames      = (Param RecommendationNames)
                recommendationSeverities = (Param RecommendationSeverities)
                recommendationStates     = (Param RecommendationStates)
                logicAppResourceId       = (Param LogicAppResourceId)
                logicAppTrigger          = (Param LogicAppTrigger)
            }
        }
    }
}

Its deployment templates are written beside it:

Source: built-in-policies/policyDefinitions/Security Center/ASC_WorkflowAutomationASCRecommendations_DINE.json in Azure/azure-policy, under the MIT licence.