Home NewsX Custom Policy- Reusable Logs Templates

Custom Policy- Reusable Logs Templates

by info.odysseyx@gmail.com
0 comment 1 views


Reusable template for sending logs to a Log Analytics workspace

challenge:

There are several approaches you can take when developing custom policies for sending logs to a Log Analytics workspace for your Azure resources. However, if a customer wants a custom policy for all Azure resources in their environment, simply copying and pasting the same policy definition can cause problems. You might not be able to copy it completely, or the way it behaves from one Azure resource to another might be different, so you’ll need to change your logic accordingly.

way out:

To solve the problems mentioned above, you can define a standardized template that can be reused by modifying specific parts of the template depending on the Azure product you need to apply. This approach ensures consistency and reduces the risk of errors.

Below you will find two templates created with this in mind. If template 1 doesn’t work, you can reuse template 2 and test accordingly.

Template 1 (default)

This is the default template available for most Azure resources with the option to enable diagnostic settings. If this template does not work, proceed with Template 2 as defined in this document.

Reference to Template 1:

{

    "name": "(Name of Policy)",

    "type": "Microsoft.Authorization/policyDefinitions",

    "apiVersion": "2022-09-01",

    "scope": null,

    "properties": {

        "displayName": "(Policy Display name )",

        "policyType": "Custom",

        "description": "(policy description)",

        "mode": "All",

        "metadata": {

            "version": "1.0.0",

            "category": "(as per product)"

        },

        "parameters": {

            "effect": {

                "type": "String",

                "metadata": {

                    "displayName": "Effect",

                    "description": "Enable or disable the execution of the policy"

                },

                "allowedValues": [

                    "DeployIfNotExists",

                    "AuditIfNotExists",

                    "Disabled"

                ],

                "defaultValue": "DeployIfNotExists"

                

            },

            "profileNameLAW": {

                "type": "String",

                "metadata": {

                    "displayName": "Profile name",

                    "description": "The diagnostic settings profile name"

                },

                "defaultValue": "setbypolicyLAW"

            },

            "logAnalytics": {

                "type": "String",

                "metadata": {

                    "displayName": "Log Analytics workspace",

                    "description": "Select Log Analytics workspace from dropdown list. ",

                    "strongType": "omsWorkspace",

                    "assignPermissions": true

                }

            },

            "logsEnabledLAWBoolean": {

                "type": "Boolean",

                "metadata": {

                    "displayName": "Enable logs",

                    "description": "Whether to enable logs stream to the Log Analytics workspace - True or False"

                },

                "allowedValues": [

                    true,

                    false

                ],

                "defaultValue": true

            },

            "metricsEnabledLAWBoolean": {

                "type": "Boolean",

                "metadata": {

                    "displayName": "Enable logs",

                    "description": "Whether to enable logs stream to the Log Analytics workspace - True or False"

                },

                "allowedValues": [

                    true,

                    false

                ],

                "defaultValue": true

            },

            "evaluationDelay": {

                "type": "String",

                "metadata": {

                    "displayName": "Evaluation Delay",

                    "description": "Specifies when the existence of the related resources should be evaluated. The delay is only used for evaluations that are a result of a create or update resource request. Allowed values are AfterProvisioning, AfterProvisioningSuccess, AfterProvisioningFailure, or an ISO 8601 duration between 0 and 360 minutes."

                },

                "defaultValue": "AfterProvisioning"

            }

        },

        "policyRule": {

            "if": {

                "field": "type",

                "equals": "(please put resource type here)"

            },

            "then": {

                "effect": "[parameters('effect')]",

                "details": {

                    "type": "Microsoft.Insights/diagnosticSettings",

                    "evaluationDelay": "[parameters('evaluationDelay')]",

                    "name": "[parameters('profileNameLAW')]",

                    "existenceCondition": {

                        "allOf": [

                            {

                                "field": "Microsoft.Insights/diagnosticSettings/logs[*].enabled",

                                "equals": "[parameters('logsEnabledLAWBoolean')]"

                            },

                            {

                                "field": "Microsoft.Insights/diagnosticSettings/metrics[*].enabled",

                                "equals": "[parameters('metricsEnabledLAWBoolean')]"

                            },

                            {

                                "field": "Microsoft.Insights/diagnosticSettings/workspaceId",

                                "equals": "[parameters('logAnalytics')]"

                            }

                        ]

                    },

                    "roleDefinitionIds": [

                        "/providers/microsoft.authorization/roleDefinitions/749f88d5-cbae-40b8-bcfc-e573ddc772fa",

                        "/providers/microsoft.authorization/roleDefinitions/92aaf0da-9dab-42b6-94a3-d43ce8d16293"

                    ],

                    "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"

                                    },

                                    "logAnalytics": {

                                        "type": "string"

                                    },

                                    "logsEnabledLAWBoolean": {

                                        "type": "bool"

                                    },

                                    "metricsEnabledLAWBoolean": {

                                        "type": "bool"

                                    },

                                    "profileNameLAW": {

                                        "type": "string"

                                    }

                                },

                                "variables": {},

                                "resources": [

                                    {

                                        "type": "(please put resource type here)/providers/diagnosticSettings",

                                        "apiVersion": "2021-05-01-preview",

                                        "name": "[concat(parameters('resourceName'), "https://techcommunity.microsoft.com/", 'Microsoft.Insights/', parameters('profileNameLAW'))]",

                                        "location": "[parameters('location')]",

                                        "dependsOn": [],

                                        "properties": {

                                            "workspaceId": "[parameters('logAnalytics')]",

                                            "logs": [

                                                {

                                                    "categoryGroup": "allLogs",

                                                    "enabled": "[parameters('logsEnabledLAWBoolean')]"

                                                }

                                            ],

                                            "metrics": [

                                                {

                                                    "category": "AllMetrics",

                                                    "enabled": "[parameters('metricsEnabledLAWBoolean')]"

                                                }

                                            ]

                                        }

                                    }

                                ],

                                "outputs": {}

                            },

                            "parameters": {

                                "location": {

                                    "value": "[field('location')]"

                                },

                                "resourceName": {

                                    "value": "[field('fullName')]"

                                },

                                "logAnalytics": {

                                    "value": "[parameters('logAnalytics')]"

                                },

                                "logsEnabledLAWBoolean": {

                                    "value": "[parameters('logsEnabledLAWBoolean')]"

                                },

                                "metricsEnabledLAWBoolean": {

                                    "value": "[parameters('metricsEnabledLAWBoolean')]"

                                },

                                "profileNameLAW": {

                                    "value": "[parameters('profileNameLAW')]"

                                }

                            }

                        }

                    }

                }

            }

        }

    }

}

Use Case for Template 1

Let’s use Application Insights to test the above template and see how it works.

Step 1: Create a policy definition in the Azure portal, providing your subscription and policy name

Shikhaghildiyal_0-1727767428942.png

Step 2: Copy the template and add it to the policy rules within your policy definition.

Shikhaghildiyal_1-1727767500863.png

Step 3: If applicable, update the policy name, resource type as specified in the template, and then save the policy.

Shikhaghildiyal_2-1727767589459.png

Step 4: Once saved, click Assign and assign the policy.

Shikhaghildiyal_3-1727767632746.png

Step 5: Now check the compliance report and see if any resources are marked as dissatisfied or non-compliant and take necessary action accordingly.

Shikhaghildiyal_4-1727767898953.png

Template 2 (with count variable)

In certain scenarios, the default template (Template 1) may not be sufficient, especially when dealing with compliance issues. One common issue you may encounter is incorrect compliance results, where your Azure resources return ambiguous or incorrect compliance status, such as: [true, false]. These inconsistencies can make it difficult to properly assess resource compliance, especially in environments with many Azure resources.

To alleviate this, we introduce Template 2, which leverages count variables to provide a more accurate and reliable logging mechanism for sending logs to a Log Analytics workspace. By including count variables, this template ensures compliance status is clearly and accurately displayed in logs, eliminating false or misleading messages.

Reference for Template 2:



{
    "name": "(Name of Policy)",
    "type": "Microsoft.Authorization/policyDefinitions",
    "apiVersion": "2022-09-01",
    "scope": null,
    "properties": {
        "displayName": "(Policy Display Name)",
        "policyType": "Custom",
        "description": "(policy description )",
        "mode": "All",
        "metadata": {
            "version": "1.0.0",
            "category": "(as per product)"
        },
        "parameters": {
            "profileNameLAW": {
                "type": "String",
                "metadata": {
                    "displayName": "Profile name",
                    "description": "The diagnostic settings profile name"
                },
                "defaultValue": "setbypolicyLAW"
            },
            "evaluationDelay": {
                "type": "String",
                "metadata": {
                    "displayName": "Evaluation Delay",
                    "description": "Specifies when the existence of the related resources should be evaluated. The delay is only used for evaluations that are a result of a create or update resource request. Allowed values are AfterProvisioning, AfterProvisioningSuccess, AfterProvisioningFailure, or an ISO 8601 duration between 0 and 360 minutes."
                },
                "defaultValue": "AfterProvisioning"
            },
            "effect": {
                "type": "String",
                "metadata": {
                    "displayName": "Effect",
                    "description": "Enable or disable the execution of the policy"
                },
                "allowedValues": [
                    "DeployIfNotExists",
                    "AuditIfNotExists",
                    "Disabled"
                ],
                "defaultValue": "DeployIfNotExists"
            },
            "logAnalytics": {
                "type": "String",
                "metadata": {
                    "displayName": "Log Analytics workspace",
                    "description": "Select the Log Analytics workspace from dropdown list",
                    "strongType": "omsWorkspace",
                    "assignPermissions": true
                }
            },
            "metricsEnabledLAWBoolean": {
                "type": "Boolean",
                "metadata": {
                    "displayName": "Enable metrics",
                    "description": "Whether to enable metrics stream to the Log Analytics workspace - True or False"
                },
                "allowedValues": [
                    true,
                    false
                ],
                "defaultValue": true
            },
            "logsEnabledLAWBoolean": {
                "type": "Boolean",
                "metadata": {
                    "displayName": "Enable logs",
                    "description": "Whether to enable logs stream to the Log Analytics workspace - True or False"
                },
                "allowedValues": [
                    true,
                    false
                ],
                "defaultValue": true
            }
        },
        "policyRule": {
            "if": {
                "field": "type",
                "equals": "(please put resource type here)"
            },
            "then": {
                "effect": "[parameters('effect')]",
                "details": {
                    "type": "Microsoft.Insights/diagnosticSettings",
                    "name": "[parameters('profileNameLAW')]",
                    "evaluationDelay": "[parameters('evaluationDelay')]",
                    "roleDefinitionIds": [
                        "/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"
                    ],
                    "existenceCondition": {
                        "allOf": [
                            {
                                "count": {
                                    "field": "Microsoft.Insights/diagnosticSettings/logs[*]",
                                    "where": {
                                        "allOf": [
                                            {
                                                "field": "Microsoft.Insights/diagnosticSettings/logs[*].enabled",
                                                "equals": "true"
                                            },
                                            {
                                                "field": "microsoft.insights/diagnosticSettings/logs[*].categoryGroup",
                                                "equals": "allLogs"
                                            }
                                        ]
                                    }
                                },
                                "greaterorEquals": 1
                            },
                            {
                                "field": "Microsoft.Insights/diagnosticSettings/metrics[*].enabled",
                                "equals": "[parameters('metricsEnabledLAWBoolean')]"
                            }
                        ]
                    },
                    "deployment": {
                        "properties": {
                            "mode": "incremental",
                            "template": {
                                "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
                                "contentVersion": "1.0.0.0",
                                "parameters": {
                                    "resourceName": {
                                        "type": "string"
                                    },
                                    "logAnalytics": {
                                        "type": "string"
                                    },
                                    "logsEnabledLAWBoolean": {
                                        "type": "bool"
                                    },
                                    "metricsEnabledLAWBoolean": {
                                        "type": "bool"
                                    },
                                    "profileNameLAW": {
                                        "type": "string"
                                    },
                                    "location": {
                                        "type": "string"
                                    }
                                },
                                "variables": {},
                                "resources": [
                                    {
                                        "type": "(please put resource type here)/providers/diagnosticSettings",
                                        "apiVersion": "2021-05-01-preview",
                                        "name": "[concat(parameters('resourceName'), "https://techcommunity.microsoft.com/", 'Microsoft.Insights/', parameters('profileName'))]",
                                        "location": "[parameters('location')]",
                                        "dependsOn": [],
                                        "properties": {
                                            "workspaceId": "[parameters('logAnalytics')]",
                                            "metrics": [
                                                {
                                                    "category": "AllMetrics",
                                                    "timeGrain": null,
                                                    "enabled": "[parameters('metricsEnabledLAWBoolean')]"
                                                }
                                            ],
                                            "logs": [
                                                {
                                                    "categoryGroup": "allLogs",
                                                    "enabled": "[parameters('logsEnabledLAWBoolean')]"
                                                }
                                            ]
                                        }
                                    }
                                ],
                                "outputs": {}
                            },
                            "parameters": {
                                "profileNameLAW": {
                                    "value": "[parameters('profileNameLAW')]"
                                },
                                "logAnalytics": {
                                    "value": "[parameters('logAnalytics')]"
                                },
                                "metricsEnabledLAWBoolean": {
                                    "value": "[parameters('metricsEnabledLAWBoolean')]"
                                },
                                "logsEnabledLAWBoolean": {
                                    "value": "[parameters('logsEnabledLAWBoolean')]"
                                },
                                "location": {
                                    "value": "[field('location')]"
                                },
                                "resourceName": {
                                    "value": "[field('name')]"
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

Use cases for Template 2

Using template 1 will cause issues for compliance reasons, so we will use a function app to test the above template.

Step 1: Create a policy definition in the Azure portal, providing your subscription and policy name

Shikhaghildiyal_0-1727773133097.png

Step 2: Copy the template and add it to the policy rules within your policy definition.

Shikhaghildiyal_1-1727773161129.png

Step 3: If applicable, update the policy name, resource type as specified in the template, and then save the policy.

Shikhaghildiyal_2-1727773187347.png

Step 4: Once saved, click Assign and assign the policy.

Shikhaghildiyal_3-1727773223239.png

Step 5: Now check the compliance report and see if any resources are marked as dissatisfied or non-compliant and take necessary action accordingly.

Shikhaghildiyal_0-1727773454108.png





Source link

You may also like

Leave a Comment

Our Company

Welcome to OdysseyX, your one-stop destination for the latest news and opportunities across various domains.

Newsletter

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

Laest News

@2024 – All Right Reserved. Designed and Developed by OdysseyX