Create a policy to deploy the diagnostic setting to both Log Analytic workspace and storage account - arm-template

I want to write a policy to deploys the diagnostic settings for Azure Activity to stream subscriptions audit logs to a Log Analytics workspace to monitor subscription-level events and at the same time archive to a storage account. Or a policy to deploy the diagnostic settings for Azure Activity to store log at storage account. I try to run my code but it's just noti block
{
"properties": {
"displayName": "Configure Azure Activity logs to stream to specified Log Analytics workspace",
"mode": "All",
"description": "Deploys the diagnostic settings for Azure Activity to stream subscriptions audit logs to a Log Analytics workspace to monitor subscription-level events",
"metadata": {
"version": "1.0.0",
"category": "Monitoring"
},
"parameters": {
"logAnalytics": {
"type": "String",
"metadata": {
"displayName": "Primary Log Analytics workspace",
"description": "If this workspace is outside of the scope of the assignment you must manually grant 'Log Analytics Contributor' permissions (or similar) to the policy assignment's principal ID.",
"strongType": "omsWorkspace",
"assignPermissions": true
}
},
"effect": {
"type": "String",
"metadata": {
"displayName": "Effect",
"description": "Enable or disable the execution of the policy"
},
"allowedValues": [
"DeployIfNotExists",
"Disabled"
],
"defaultValue": "DeployIfNotExists"
},
"logsEnabled": {
"type": "String",
"metadata": {
"displayName": "Enable logs",
"description": "Whether to enable logs stream to the Log Analytics workspace - True or False"
},
"allowedValues": [
"True",
"False"
],
"defaultValue": "True"
},
"existingDiagnosticsStorageAccountName": {
"type": "string",
"metadata": {
"description": "Specify the name of an existing storage account for diagnostics."
}
},
"existingDiagnosticsStorageAccountResourceGroup": {
"type": "string",
"metadata": {
"description": "Specify the resource group name of an existing storage account for diagnostics."
}
}
},
"policyRule": {
"if": {
"field": "type",
"equals": "Microsoft.Resources/subscriptions"
},
"then": {
"effect": "[parameters('effect')]",
"details": {
"type": "Microsoft.Insights/diagnosticSettings",
"deploymentScope": "Subscription",
"existenceScope": "Subscription",
"existenceCondition": {
"allOf": [
{
"field": "Microsoft.Insights/diagnosticSettings/logs.enabled",
"equals": "[parameters('logsEnabled')]"
},
{
"field": "Microsoft.Insights/diagnosticSettings/workspaceId",
"equals": "[parameters('logAnalytics')]"
},
{
"field":"Microsoft.Insights/diagnosticSettings/storageAccountId",
"equals":"[parameters('existingDiagnosticsStorageAccountName')]"
}
]
},
"deployment": {
"location": "southeastasia",
"properties": {
"mode": "incremental",
"template": {
"$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"logAnalytics": {
"type": "string"
},
"logsEnabled": {
"type": "string"
}
},
"variables": {},
"resources": [
{
"name": "DiagnosticToSubscription",
"type": "Microsoft.Insights/diagnosticSettings",
"apiVersion": "2017-05-01-preview",
"location": "Global",
"properties": {
"workspaceId": "[parameters('logAnalytics')]",
"logs": [
{
"category": "Administrative",
"enabled": "[parameters('logsEnabled')]"
},
{
"category": "Security",
"enabled": "[parameters('logsEnabled')]"
},
{
"category": "ServiceHealth",
"enabled": "[parameters('logsEnabled')]"
},
{
"category": "Alert",
"enabled": "[parameters('logsEnabled')]"
},
{
"category": "Recommendation",
"enabled": "[parameters('logsEnabled')]"
},
{
"category": "Policy",
"enabled": "[parameters('logsEnabled')]"
},
{
"category": "Autoscale",
"enabled": "[parameters('logsEnabled')]"
},
{
"category": "ResourceHealth",
"enabled": "[parameters('logsEnabled')]"
}
],
"storageAccountId": "[extensionResourceId(format('/subscriptions/{0}/resourceGroups/{1}', subscription().subscriptionId, parameters('existingDiagnosticsStorageAccountResourceGroup')), 'Microsoft.Storage/storageAccounts', parameters('existingDiagnosticsStorageAccountName'))]",
"metrics": [
{
"timeGrain": "AllMetrics",
"enabled": "[parameters('diagnosticsEnabled')]",
"retentionPolicy": {
"days": 90,
"enabled": "[parameters('diagnosticsEnabled')]"
}
}
]
}
}
],
"outputs": {}
},
"parameters": {
"logAnalytics": {
"value": "[parameters('logAnalytics')]"
},
"logsEnabled": {
"value": "[parameters('logsEnabled')]"
},
"existingDiagnosticsStorageAccountResourceGroup": {
"value": "[parameters('existingDiagnosticsStorageAccountResourceGroup')]"
},
"existingDiagnosticsStorageAccountName": {
"value": "[parameters('existingDiagnosticsStorageAccountName')]"
}
}
}
},
"roleDefinitionIds": [
"/providers/microsoft.authorization/roleDefinitions/749f88d5-cbae-40b8-bcfc-e573ddc772fa",
"/providers/microsoft.authorization/roleDefinitions/92aaf0da-9dab-42b6-94a3-d43ce8d16293"
]
}
}
}
}
}

To achieve the above requirement you may follow the below workaround.
ARM TEMPLATE:-
{
"properties": {
"displayName": "Deploy Diagnostic Settings for Storage Accounts to Log Analytics",
"mode": "Indexed",
"description": "Deploys the diagnostic settings for Storage Accounts to log read/write/delete and retain logs.",
"metadata": {
"category": "Monitoring"
},
"parameters": {
"effect": {
"type": "String",
"metadata": {
"displayName": "Effect",
"description": "Enable or disable the execution of the policy"
},
"allowedValues": [
"DeployIfNotExists",
"Disabled"
],
"defaultValue": "DeployIfNotExists"
},
"profileName": {
"type": "String",
"metadata": {
"displayName": "Profile Name",
"description": "The diagnostic setting profile name"
},
"default": "setbypolicy_logAnalytics"
},
"logAnalytics": {
"type": "String",
"metadata": {
"displayName": "Log Analytics workspace",
"description": "Select Log Analytics workspace from dropdown list. If this workspace is outside of the scope of the assignment you must manually grant 'Log Analytics Contributor' permissions (or similar) to the policy assignment's principal ID.",
"strongType": "omsWorkspace",
"assignPermissions": true
}
},
"metricsEnabled": {
"type": "String",
"metadata": {
"displayName": "Enable metrics",
"description": "Whether to enable metrics stream to the Event Hub - True or False"
},
"allowedValues": [
"True",
"False"
],
"defaultValue": "False"
},
"logsEnabled": {
"type": "String",
"metadata": {
"displayName": "Enable logs",
"description": "Whether to enable logs stream to the Event Hub - True or False"
},
"allowedValues": [
"True",
"False"
],
"defaultValue": "True"
}
},
"policyRule": {
"if": {
"field": "type",
"equals": "Microsoft.Storage/storageAccounts"
},
"then": {
"effect": "[parameters('effect')]",
"details": {
"type": "Microsoft.Insights/diagnosticSettings",
"name": "[parameters('profileName')]",
"existenceCondition": {
"allOf": [
{
"field": "Microsoft.Insights/diagnosticSettings/logs.enabled",
"equals": "parameters('logsEnabled')"
},
{
"field": "Microsoft.Insights/diagnosticSettings/metrics.enabled",
"equals": "parameters('metricsEnabled')]"
}
]
},
"roleDefinitionIds": [
"/providers/Microsoft.Authorization/roleDefinitions/"
],
"deployment": {
"properties": {
"mode": "Incremental",
"template": {
"$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"resourceName": {
"type": "string"
},
"logAnalytics": {
"type": "string"
},
"location": {
"type": "string"
},
"metricsEnabled": {
"type": "string"
},
"logsEnabled": {
"type": "string"
},
"profileName": {
"type": "string"
}
},
"variables": {},
"resources": [
{
"type": "Microsoft.Storage/storageAccounts/providers/diagnosticSettings",
"apiVersion": "2017-05-01-preview",
"name": "[concat(parameters('resourceName'), '/', 'Microsoft.Insights/', parameters('profileName'))]",
"location": "[parameters('location')]",
"dependsOn": [],
"properties": {
"workspaceId": "[parameters('logAnalytics')]",
"metrics": [
{
"category": "AllMetrics",
"enabled": true,
"retentionPolicy": {
"enabled": true,
"days": 365
}
}
],
"logs": [
{
"category": "Audit",
"enabled": true
},
{
"category": "Requests",
"enabled": true
}
]
}
}
],
"outputs": {}
},
"parameters": {
"location": {
"value": "[field('location')]"
},
"resourceName": {
"value": "[field('name')]"
},
"profileName": {
"value": "[parameters('profileName')]"
},
"metricsEnabled": {
"value": "[parameters('metricsEnabled')]"
},
"logsEnabled": {
"value": "[parameters('logsEnabled')]"
},
"logAnalytics": {
"value": "[parameters('logAnalytics')]"
}
}
}
}
}
}
}
}
}
For for information please refer this MICROSOFT DOCUMENTATION

Related

Azure policy to create locks on all vm's in a subscription

I am using this code below to attempt to lock just the VM's in a subscription, but the effect is to place a lock on the Resource Groups. How can I make this apply only to vm's only and not the RG?
{
"properties": {
"displayName": "All Azure Vm's should be Delete Locked",
"mode": "Indexed",
"description": "This policy will add an CanNotDelete Resource Lock.",
"metadata": {
"version": "1.1.0",
"category": "Compute"
},
"parameters": {
"effect" : {
"type" : "String",
"metadata" : {
"displayName" : "Effect",
"description" : "Enable a Delete Lock"
},
"allowedValues" : [
"CanNotDelete",
"ReadOnly",
"NotSpecified"
],
"defaultValue": "CanNotDelete"
}
},
"policyRule": {
"if": {
"allOf": [
{
"field": "type",
"equals": "Microsoft.Compute/virtualMachines"
}
]
},
"then": {
"effect": "auditIfNotExists",
"details": {
"type": "Microsoft.Authorization/locks",
"existenceCondition": {
"field": "Microsoft.Authorization/locks/level",
"equals": "CanNotDelete"
}
}
}
}
}
}
Created a policy to place locks on Virtual machines in Azure. Locks are placed on the Resource Group, which does lock the vm, but I only want the lock on the vm and not the resource group.
You are missing the deployment part of deployment template.
https://learn.microsoft.com/en-us/azure/governance/policy/samples/pattern-deploy-resources#deployment-template
You can only assign the resource lock on a single resource, if you do not want to assign it on the resource group:
https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/scope-extension-resources?tabs=azure-cli#apply-to-resource
For a single resource resource lock, then you need to use and define a scope:
https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/lock-resources?tabs=json#template
Under the "resources": [ you can do multiple deployments, see code #2:
#1
{
"properties": {
"displayName": "All Azure Vm's should be Delete Locked",
"description": "This policy will add an CanNotDelete Resource Lock.",
"mode": "all",
"metadata": {
"version": "1.1.0",
"category": "Compute"
},
"parameters": {
"effect": {
"type": "String",
"metadata": {
"displayName": "Effect",
"description": "Enable a Delete Lock"
},
"allowedValues": [
"CanNotDelete",
"ReadOnly",
"NotSpecified"
],
"defaultValue": "CanNotDelete"
}
},
"policyRule": {
"if": {
"field": "type",
"equals": "Microsoft.Compute/virtualMachines"
},
"then": {
"effect": "DeployIfNotExists",
"details": {
"type": "Microsoft.Authorization/locks",
"existenceCondition": {
"field": "Microsoft.Authorization/locks/level",
"equals": "[parameters('effect')]"
},
"roleDefinitionIds": [
"/providers/Microsoft.Authorization/roleDefinitions/8e3af657-a8ff-443c-a75c-2fe8c4bcb635"
],
"deployment": {
"properties": {
"mode": "incremental",
"template": {
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json",
"contentVersion": "1.0.0.0",
"parameters": {},
"variables": {
"vmName": "vm-niclas01"
},
"resources": [
{
"type": "Microsoft.Authorization/locks",
"apiVersion": "2020-05-01",
"name": "DenyDelete",
"scope": "[concat('Microsoft.Compute/virtualMachines/', variables('vmName'))]",
"properties": {
"level": "CanNotDelete",
"notes": "Prevents deletion of resource."
}
}
]
}
}
}
}
}
}
}
}
#2 - Deploy lock on multiple VMs, not on RG:
{
"properties": {
"displayName": "Test 2 - All Azure Vm's should be Delete Locked",
"policyType": "Custom",
"mode": "All",
"metadata": {
"version": "1.1.0"
},
"parameters": {
"effect": {
"type": "String",
"metadata": {
"displayName": "Effect",
"description": "Enable a Delete Lock"
},
"allowedValues": [
"CanNotDelete",
"ReadOnly",
"NotSpecified"
],
"defaultValue": "CanNotDelete"
},
"vmName": {
"type": "Array",
"metadata": {
"displayName": "VM Names",
"description": "The list of VM names that should have resource locks"
},
"allowedValues": [
"vm-niclas01",
"vm-niclas02",
"vm-linuxniclas"
]
}
},
"policyRule": {
"if": {
"allOf": [
{
"field": "name",
"in": "[parameters('vmName')]"
},
{
"field": "type",
"equals": "Microsoft.Compute/virtualMachines"
}
]
},
"then": {
"effect": "DeployIfNotExists",
"details": {
"type": "Microsoft.Authorization/locks",
"existenceCondition": {
"field": "Microsoft.Authorization/locks/level",
"equals": "[parameters('effect')]"
},
"roleDefinitionIds": [
"/providers/Microsoft.Authorization/roleDefinitions/8e3af657-a8ff-443c-a75c-2fe8c4bcb635"
],
"deployment": {
"properties": {
"mode": "incremental",
"template": {
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json",
"contentVersion": "1.0.0.0",
"parameters": {
"vmName": {
"type": "Array"
}
},
"variables": {
"vmName1": "[concat('/', parameters('vmName')[0])]",
"vmName2": "[concat('/', parameters('vmName')[1])]"
},
"resources": [
{
"type": "Microsoft.Authorization/locks",
"apiVersion": "2020-05-01",
"name": "DenyDelete",
"scope": "[concat('Microsoft.Compute/virtualMachines', variables('vmName1'))]",
"properties": {
"level": "CanNotDelete",
"notes": "Prevents deletion of resource."
}
},
{
"type": "Microsoft.Authorization/locks",
"apiVersion": "2020-05-01",
"name": "DenyDelete",
"scope": "[concat('Microsoft.Compute/virtualMachines/', variables('vmName2'))]",
"properties": {
"level": "CanNotDelete",
"notes": "Prevents deletion of resource."
}
}
],
"outputs": {}
},
"parameters": {
"vmName": {
"value": "[parameters('vmName')]"
}
}
}
}
}
}
}
}
}
3 VMs in the same RG:
Policy assignment with parameter:
Resource Lock deployed:
Resource Lock not deployed, because it is not part of policy parameter:

Why does Microsoft.DocumentDB/databaseAccounts/backupPolicy.type not evaluate to Continuous in Azure Policies?

I'm creating a policy in Microsoft Azure that checks the backup policy of Cosmos DB accounts in DeployIfNotExists mode. It checks the Microsoft.DocumentDB/databaseAccounts/backupPolicy.type property. The Cosmos DBs should have continuous backup enabled. I've tested the policy by assigning it to a resource group with Cosmos DBs with continuous backup and periodic backup. All Cosmos DBs are evaluated to be compliant, even the ones with "Periodic" backup policy. Why does this not work?
Policy:
{
"properties": {
"displayName": "Deploy Continuous Backup for Cosmos DB",
"policyType": "Custom",
"mode": "Indexed",
"parameters": {
"effect": {
"type": "String",
"metadata": {
"displayName": "Effect",
"description": "Enable or disable the execution of the policy"
},
"allowedValues": [
"DeployIfNotExists",
"Disabled"
],
"defaultValue": "DeployIfNotExists"
}
},
"policyRule": {
"if": {
"field": "type",
"equals": "Microsoft.DocumentDB/databaseAccounts"
},
"then": {
"effect": "[parameters('effect')]",
"details": {
"type": "Microsoft.DocumentDB/databaseAccounts",
"roleDefinitionIds": [
"/providers/microsoft.authorization/roleDefinitions/5bd9cd88-fe45-4216-938b-f97437e15450",
"/providers/microsoft.authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"
],
"existenceCondition": {
"field": "Microsoft.DocumentDB/databaseAccounts/backupPolicy.type",
"equals": "Continuous"
},
"deployment": {
"properties": {
"mode": "incremental",
"template": {
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"location": {
"type": "string"
},
"kind": {
"type": "string"
},
"resourceName": {
"type": "string"
}
},
"variables": {},
"resources": [
{
"apiVersion": "2016-03-31",
"name": "[parameters('resourceName')]",
"location": "[parameters('location')]",
"type": "Microsoft.DocumentDB/databaseAccounts",
"kind": "[parameters('kind')]",
"properties": {
"backupPolicy": {
"type": "Continuous"
},
"databaseAccountOfferType": "Standard",
"locations": [
{
"locationName": "[parameters('location')]"
}
],
"createMode": "Default"
}
}
],
"outputs": {}
},
"parameters": {
"location": {
"value": "[field('location')]"
},
"kind": {
"value": "[field('kind')]"
},
"resourceName": {
"value": "[field('name')]"
}
}
}
}
}
}
}
}
}

DeployIfnotexists azure policy failing with error

I am new to azure policy and i am trying to write a deployifnotexists policy for storage account which will enable point-in-time restore for containers with 300days. It does error while deploying, error saying HttpResourceNotFound and random http request url. I would like to know whether the policy is correct or not and Here is the code i created which i am using:
{
"properties": {
"displayName": "storage-pointintime",
"policyType": "Custom",
"mode": "All",
"metadata": {
},
"parameters": {
"effect": {
"type": "String",
"metadata": {
"displayName": "Effect",
"description": "Enable or disable the execution of the policy."
},
"allowedValues": [
"DeployIfNotExists",
"Deny",
"Audit"
],
"defaultValue": "DeployIfNotExists"
},
"retentionInDays": {
"type": "String",
"metadata": {
"displayName": "Retention Days",
"description": "Set the number of Retention Days."
},
"defaultValue": "300"
}
},
"policyRule": {
"if": {
"allOf": [
{
"field": "type",
"equals": "Microsoft.Storage/storageAccounts"
}
]
},
"then": {
"effect": "[parameters('effect')]",
"details": {
"type": "Microsoft.Storage/storageAccounts/blobServices/restorePolicy",
"roleDefinitionIds": [
"/providers/Microsoft.Authorization/roleDefinitions/<id>"
],
"existenceCondition": {
"field": "Microsoft.Storage/storageAccounts/blobServices/restorePolicy.days",
"equals": "[parameters('retentionInDays')]"
},
"deployment": {
"properties": {
"mode": "incremental",
"template": {
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"storageAccounts": {
"type": "string"
},
"retentionDays": {
"type": "string"
}
},
"resources": [
{
"name": "[concat(parameters('storageAccounts'),'/default')]",
"type": "Microsoft.Storage/storageAccounts/blobServices/restorePolicy",
"apiVersion": "2021-04-01",
"properties": {
"retentionInDays": "[parameters('retentionDays')]"
}
}
]
},
"retentionDays": {
"value": "[parameters('retentionInDays')]"
}
}
}
}
}
}
}
}
If you want to enable point-in-time restore for containers, the type should be Microsoft.Storage/storageAccounts/blobServices. Azure ARM template does not provide type Microsoft.Storage/storageAccounts/blobServices/restorePolicy.
For example
{
"name": "[concat(parameters('storageAccountName'), '/default')]",
"type": "Microsoft.Storage/storageAccounts/blobServices",
"apiVersion": "2019-06-01",
"properties": {
"restorePolicy": {
"enabled": "[parameters('isContainerRestoreEnabled')]",
"days": "[parameters('containerRestorePeriodDays')]"
},
"deleteRetentionPolicy": {
"enabled": "[parameters('isBlobSoftDeleteEnabled')]",
"days": "[parameters('blobSoftDeleteRetentionDays')]"
},
"containerDeleteRetentionPolicy": {
"enabled": "[parameters('isContainerSoftDeleteEnabled')]"
},
"changeFeed": {
"enabled": "[parameters('changeFeed')]"
},
"isVersioningEnabled": "[parameters('isVersioningEnabled')]"
},
"dependsOn": [
"[concat('Microsoft.Storage/storageAccounts/', parameters('storageAccountName'))]"
]
}
For more details, please refer to here and here.

How to create Activity logs diagnostic setting for Azure resources using ARM template

We are referring this documentation here which talks about Creating diagnostic setting in Azure using a Resource Manager template.
We have managed to provision resources with ARM template along with diagnostic setting for resource logs, however snippet in the documentation to enable the activity logs diagnostic setting does not seem to work as the template deployment command (new-azresourcegroupdeployment) returns the Bad request error.
New-AzResourceGroupDeployment : Resource Microsoft.Insights/diagnosticSettings 'test-vnet' failed with message '{
"Code": "BadRequest",
"Message": ""
}'
Here is the template (trimmed some code to avoid noise)
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
...
},
"variables": {
...
},
"resources": [
{
"apiVersion": "2018-08-01",
"type": "Microsoft.Network/virtualNetworks",
"name": "[parameters('virtualNetworkName')]",
"location": "[parameters('resourceLocation')]",
"properties": {
"addressSpace": {
"addressPrefixes": [
"[parameters('addressPrefix')]"
]
},
"subnets": "[parameters('subnets')]",
"dhcpOptions": {
"dnsServers": "[parameters('dnsServers')]"
}
},
"resources":
[
{
"type": "Microsoft.Insights/diagnosticSettings",
"apiVersion": "2017-05-01-preview",
"name": "[variables('diagnosticsSettingsName')]",
"dependsOn": [
"[parameters('virtualNetworkName')]"
],
"location": "global",
"properties":
{
"storageAccountId": "..valid_id_here",
"logs":
[
{
"category": "Administrative",
"enabled": true
},
{
"category": "Security",
"enabled": true
},
{
"category": "ServiceHealth",
"enabled": true
},
{
"category": "ResourceHealth",
"enabled": true
}
]
}
}
]
}
],
"outputs": {
..
}
The documentation here which you are referring for Creating diagnostic settings.
So If you will check the Deployment Methods in this document, it says that you can deploy Resource Manager templates using any valid method including PowerShell and CLI. Diagnostic settings for Activity log must deploy to a subscription using az deployment create for CLI or New-AzDeployment for PowerShell.
Use New-AzDeployment instead of New-AzResourceGroupDeployment to deploy the ARM Template.
Hope this helps!!
This policy works for me, note that it is Subscription level deployment:
{
"properties": {
"displayName": "Deploy diagnostic setting profile for Subscription Activity Logs to Log Analytics workspace",
"description": "Deploys the diagnostic settings for Subscription Activity Logs to stream to a regional Log Analytics workspace when any Subscription which is missing this diagnostic settings is created or updated.",
"mode": "All",
"metadata": {
"version": "1.0.0",
"category": "audit"
},
"parameters": {
"effect": {
"type": "String",
"metadata": {
"displayName": "Effect",
"description": "Enable or disable the execution of the policy"
},
"allowedValues": [
"DeployIfNotExists",
"Disabled"
],
"defaultValue": "DeployIfNotExists"
},
"settingsProfileName": {
"type": "String",
"metadata": {
"displayName": "Settings profile name",
"description": "The diagnostic settings profile name"
},
"defaultValue": "setbypolicy_logAnalytics"
},
"logAnalyticsResourceId": {
"type": "String",
"metadata": {
"displayName": "Log Analytics resourceId",
"description": "Set to full Log Analytics workspace resorceId. If this workspace is outside of the scope of the assignment you must manually grant 'Log Analytics Contributor' permissions (or similar) to the policy assignment's principal ID."
}
}
},
"policyRule": {
"if": {
"field": "type",
"equals": "Microsoft.Resources/subscriptions"
},
"then": {
"effect": "[parameters('effect')]",
"details": {
"type": "Microsoft.Insights/diagnosticSettings",
"name": "[parameters('settingsProfileName')]",
"existenceCondition": {
"allOf": [
{
"field": "Microsoft.Insights/diagnosticSettings/workspaceId",
"equals": "[parameters('logAnalyticsResourceId')]"
}
]
},
"deploymentScope": "subscription",
"roleDefinitionIds": [
"/providers/microsoft.authorization/roleDefinitions/749f88d5-cbae-40b8-bcfc-e573ddc772fa",
"/providers/microsoft.authorization/roleDefinitions/92aaf0da-9dab-42b6-94a3-d43ce8d16293"
],
"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": {
"settingsProfileName": {
"type": "string"
},
"logAnalyticsResourceId": {
"type": "string"
}
},
"variables": {},
"resources": [
{
"type": "Microsoft.Insights/diagnosticSettings",
"apiVersion": "2017-05-01-preview",
"name": "[parameters('settingsProfileName')]",
"properties": {
"workspaceId": "[parameters('logAnalyticsResourceId')]",
"logs": [
{
"category": "Administrative",
"enabled": "true"
},
{
"category": "Alert",
"enabled": "true"
},
{
"category": "Autoscale",
"enabled": "true"
},
{
"category": "Policy",
"enabled": "true"
},
{
"category": "Recommendation",
"enabled": "true"
},
{
"category": "ResourceHealth",
"enabled": "true"
},
{
"category": "Security",
"enabled": "true"
},
{
"category": "ServiceHealth",
"enabled": "true"
}
]
}
}
],
"outputs": {}
},
"parameters": {
"settingsProfileName": {
"value": "[parameters('settingsProfileName')]"
},
"logAnalyticsResourceId": {
"value": "[parameters('logAnalyticsResourceId')]"
}
}
}
}
}
}
}
}
}

Azure Policy DeployIfNotExists : Retention days must be greater than X days for SQL server

I am trying to develop an Azure Policy (json) ensuring that for a given SQL Server with Auditing enabled (no need to check that), retention days period has been set to a value greater than X (let's say 90 days in my case).
I tried to use deployIfNotExists effect, with an existenceCondition on retentionDays field (greater than 90). In the deployment part, I set the field to 365.
I assigned the policy to a resource group in which I have a SQL Server with Auditing and retention days equal to 20.
But still, the policy appears as 'Compliant' and retentionDays remains the same. Here is the code :
"if": {
"field": "type",
"equals": "Microsoft.Sql/servers"
},
"then": {
"effect": "deployIfNotExists",
"details": {
"type": "Microsoft.Sql/servers/auditingSettings",
"roleDefinitionIds": [
"/providers/Microsoft.Authorization/roleDefinitions/XXXXXXXX"
],
"existenceCondition": {
"field": "Microsoft.Sql/servers/auditingSettings/retentionDays",
"greater": "90"
},
"deployment": {
"properties": {
"mode": "incremental",
"template": {
"$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"resourceName": {
"type": "string"
},
"location": {
"type": "string"
},
"retentionDays": {
"type": "string"
}
},
"variables": {},
"resources": [{
"type": "Microsoft.Sql/servers/auditingSettings",
"apiVersion": "2017-03-01-preview",
"name": "[concat(parameters('resourceName'), '/Default')]",
"location": "[parameters('location')]",
"dependsOn": [],
"properties": {
"retentionDays": "[parameters('retentionDays')]"
}
}],
"outputs": {}
},
"parameters": {
"location": {
"value": "[field('location')]"
},
"resourceName": {
"value": "[field('name')]"
},
"retentionDays": {
"value": "365"
}
}
}
}
}
}
I am wondering if I am using the right alias at the right place. Any clue ?
Thanks!
Here's my code that works!!!!
{
"properties": {
"displayName": "deploy-sql-db-backupshorttermretentionpolicies",
"policyType": "Custom",
"mode": "All",
"description": "Deploy If Not Exists backupshorttermretentionpolicies",
"parameters": {
"effect": {
"type": "String",
"metadata": {
"displayName": "Effect",
"description": "Enable or disable the execution of the policy."
},
"allowedValues": [
"DeployIfNotExists",
"Disabled"
],
"defaultValue": "DeployIfNotExists"
},
"retentionDays": {
"type": "String",
"metadata": {
"displayName": "Retention Days",
"description": "Set the number of Backup Retention Days."
},
"defaultValue": "35"
}
},
"policyRule": {
"if": {
"field": "type",
"equals": "Microsoft.Sql/servers/databases"
},
"then": {
"effect": "[parameters('effect')]",
"details": {
"type": "Microsoft.Sql/servers/databases/backupShortTermRetentionPolicies",
"name": "default",
"roleDefinitionIds": [
"/providers/microsoft.authorization/roleDefinitions/####
],
"existenceCondition": {
"field": "Microsoft.Sql/servers/databases/backupShortTermRetentionPolicies/retentionDays",
"equals": "[parameters('retentionDays')]"
},
"deployment": {
"properties": {
"mode": "incremental",
"template": {
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"serverName": {
"type": "string"
},
"shortTermRetention": {
"type": "string"
}
},
"resources": [
{
"name": "[concat(parameters('serverName'),'/default')]",
"type": "Microsoft.Sql/servers/databases/backupShortTermRetentionPolicies",
"apiVersion": "2017-10-01-preview",
"properties": {
"retentionDays": "[parameters('shortTermRetention')]"
}
}
]
},
"parameters": {
"serverName": {
"value": "[field('fullname')]"
},
"shortTermRetention": {
"value": "[parameters('retentionDays')]"
}
}
}
}
}
}
}
}
}

Resources