azure policy
88 TopicsSSL/TLS connection issue troubleshooting guide
You may experience exceptions or errors when establishing TLS connections with Azure services. Exceptions are vary dramatically depending on the client and server types. A typical ones such as "Could not create SSL/TLS secure channel." "SSL Handshake Failed", etc. In this article we will discuss common causes of TLS related issue and troubleshooting steps.42KViews9likes1CommentEnable HTTPS setting on Azure App service using Azure policy
Use Case: By default, clients can connect to Azure App Service endpoints by using both HTTP or HTTPS. However it is always recommended to redirect HTTP to HTTPs because HTTPS uses the SSL/TLS protocol to provide a secure connection, which is both encrypted and authenticated. In this post , we will learn how to enable HTTPS Only setting on the Azure App service using Azure Policy. Background: Azure App Service is a fully managed platform as a service (PaaS) offering for developers. It is a HTTP-based service for hosting web applications, REST APIs, and mobile back ends. App Service not only adds the power of Microsoft Azure to your application, such as security, load balancing, autoscaling, and automated management , you can also take advantage of its DevOps capabilities, such as continuous deployment from Azure DevOps, GitHub, Docker Hub, and other sources, package management, staging environments, custom domain, and TLS/SSL certificates. Azure Policy is a service in Azure which helps to enforce organizational standards and to assess compliance. Policy evaluates resources in Azure by comparing the properties of those resources to business rules which are defined in the Policy. These business rules, described in JSON format, are known as policy definitions. To learn more about policy and how to create a policy you can refer this document. To ensure proper governance and considering the organization has a requirement to enforce HTTPS on both new and existing App services within your environment we are going to achieve this using Azure Policy. Prerequisites: An Azure Subscription. If you don't have an Azure subscription, create an Azure free account before you begin. You need to have required permissions to create and manage Azure policy definitions in your subscription. You can refer to Resource Policy Contributor or Security Admin role. Since this policy is using DeployIfNotExists effect, policy assignments will require a managed identity to do remediation. Create a custom policy to Enable HTTPS on App Service: In the Azure portal, select All services > search for Policy > go to Definitions > click + Policy definition. Select Definition location by clicking on the ellipsis [...] and choose your management group or subscription. Fill Name field with your policy definition name like 'Enable HTTPS on App Service' and add the Description. Select appropriate Category for your policy, you can create a new one or use existing one like 'App Service'. Here is the JSON Policy definition which you need to add in the Policy Rule section and then click on Save. DISCLAIMER: Below sample policy definition is not supported under any Microsoft standard support program or service. This is intended to be used in non-production environment only. The sample scripts are provided AS IS without warranty of any kind. Microsoft further disclaims all implied warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance of the sample scripts and documentation remains with you. In no event shall Microsoft, its authors, owners of this GitHub repro, or anyone else involved in the creation, production, or delivery of the scripts be liable for any damages whatsoever (including without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the sample scripts or documentation, even if Microsoft has been advised of the possibility of such damages. { "mode": "All", "policyRule": { "if": { "allOf": [ { "field": "type", "equals": "Microsoft.Web/sites" }, { "field": "kind", "like": "app*" } ] }, "then": { "effect": "[parameters('effect')]", "details": { "type": "Microsoft.Web/sites", "name": "[field('name')]", "existenceCondition": { "field": "Microsoft.Web/sites/httpsOnly", "equals": "true" }, "roleDefinitionIds": [ "/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c" ], "deployment": { "properties": { "mode": "incremental", "parameters": { "webAppName": { "value": "[field('name')]" }, "location": { "value": "[field('location')]" }, "kind": { "value": "[field('kind')]" } }, "template": { "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "webAppName": { "type": "string" }, "location": { "type": "string" }, "kind": { "type": "string" } }, "resources": [ { "type": "Microsoft.Web/sites", "apiVersion": "2021-02-01", "name": "[parameters('webAppName')]", "location": "[parameters('location')]", "kind": "[parameters('kind')]", "properties": { "httpsOnly": "true" } } ] } } } } } }, "parameters": { "effect": { "type": "String", "metadata": { "displayName": "Effect", "description": "Enable or disable the execution of the policy" }, "allowedValues": [ "DeployIfNotExists", "AuditIfNotExists", "Disabled" ], "defaultValue": "DeployIfNotExists" } } } Ensure that the roleDefinitionIds contains enough permissions to enable HTTPS settings on the resource, you can select Contributor role. If the ExistenceCondition evaluates to true, the policy doesn't trigger the deployment and if the condition evaluates to false the HTTPS deployment happens. Refer to this document to learn more about DeployIfNotExists and ExistenceCondition. Assign the custom policy: Open the Azure portal ,select All services > search for Policy > go to Assignments> select Assign policy. On the Assign Policy page, set the Scope by selecting the ellipsis and then selecting either a management group or subscription. Optionally, select a resource group. A scope determines what resources or grouping of resources the policy assignment gets enforced on. Then use the Select button at the bottom of the Scope page. Resources can be excluded based on the Scope. Exclusions start at one level lower than the level of the Scope. Exclusions are optional, so leave it blank for now. Select the Policy definition ellipsis to open the list of available definitions. Search for the custom policy 'Enable HTTPS on App Service' that you have created in the previous step and then click on Select. The Assignment name is automatically populated with the policy name you selected, but you can change it. For this example, leave Enable HTTPS on App Service. You can also add an optional Description. The description provides details about this policy assignment. Assigned by will automatically fill based on who is logged in. This field is optional, so custom values can be entered. Leave policy enforcement Enabled. For more information, see Policy assignment - enforcement mode. Select Next at the bottom of the page or the Parameters tab at the top of the page to move to the next segment of the assignment wizard. If the policy definition selected on the Basics tab included parameters, they are configured on this tab. Since our definition has parameters (DeployIfNotExists , AuditIfNotExists , Disabled) , by default DeployIfNotExists is selected. In the Remediation tab, you can see that "Create a Managed Identity" is selected by default as the policy effect is DeployIfNotExists. Policies with the deployIfNotExists and modify effect types need the ability to deploy or modify the resources To do this, choose between an existing user assigned managed identity or creating a system assigned managed identity. This identity will also be given the Contributor permissions. For more information , refer managed identities. To evaluate the existing resources, you can select "Create a remediation task" as shown below. In the next page, set your desired message in Non-compliance message field. This custom message is displayed when a resource is denied or for non-compliant resources during regular evaluation. Then click Review + Create. Review the selected options, then select Create at the bottom of the page. Verify if the policy evaluation triggered: It takes around 30 minutes for the policy assignment to be applied to the defined scope and then the evaluation cycle begins for resources within that scope against the newly assigned policy and depending on the effects used by the policy or initiative, resources are marked as compliant, non-compliant, or exempt. Also for every 24 hours, there is a standard compliance evaluation cycle which will trigger and assignments are automatically reevaluated. Also you can trigger an On demand evaluation scan. You're now ready to identify non-compliant resources to understand the compliance state of your environment. Identify non-compliant resources: Select Compliance in the left side of the page. Then locate the 'Enable HTTPS on App Service' policy assignment you created. If there are any existing App Service resources that don't have HTTPS enabled, they appear under Non-compliant resources. Remember that when a condition is evaluated against your existing App Service resources and HTTPS is not enabled, then those resources are marked as non-compliant but no action is taken on these existing resources. For this reason, we have created a remediation task during the policy assignment. On the left side, click on Remediation and locate with your Policy definition name and you can see that the existing non-compliant resources got remediated successfully. And after the remediation run, all the App Services in your environment will get marked as compliant. Now that you can verify the HTTPS setting is enabled on your App Service now. Go to your App Service > TLS/SSL settings > HTTPS Only Note : This Policy is used to enable HTTPS setting for App Service resources only. But you can use the same policy rule for function app by modifying the below field. { "field": "kind", "like": "functionapp*" } This way, we can use Azure Policy to Enable HTTPS setting on Azure App Services. To learn more about Azure Policy, refer to the following documentation Azure Policy28KViews7likes3CommentsManaging Azure Policies through Python SDK
Managing Azure Policies through Python SDK Azure Policy helps to enforce organizational standards and to assess compliance at-scale. It also helps to bring your resources to compliance through bulk remediation for existing resources and automatic remediation for added resources. Common use cases for Azure Policy include implementing governance for resource consistency, regulatory compliance, security, cost, and management. Policy definitions for these common use cases are already available in your Azure environment as built-ins to help you get started. Specifically, some useful governance actions you can enforce with Azure Policy include: Ensuring your team deploys Azure resources only to allowed regions. Enforcing the consistent application of taxonomic tags Requiring resources to send diagnostic logs to a Log Analytics workspace References: https://learn.microsoft.com/en-us/azure/governance/policy/overview https://learn.microsoft.com/en-us/azure/governance/policy/policy-glossary https://learn.microsoft.com/en-us/azure/developer/python/sdk/azure-sdk-overview We can manage Azure policies through portal, PowerShell, CLI, REST API, Bicep, ARM Templates, Terraform and SDKs. This blog will cover the policy management through Python SDK and we can use any IDE that supports Python SDK for Azure. We are using Visual Studio Code here. (https://azure.microsoft.com/en-in/products/visual-studio-code) Azure Python SDK Authentication Reference : https://learn.microsoft.com/en-us/azure/developer/python/sdk/authentication-overview Import Libraries import os from azure.identity import ClientSecretCredential from azure.identity import AzureCliCredential from azure.mgmt.authorization import AuthorizationManagementClient from azure.mgmt.resource import PolicyClient, ResourceManagementClient from azure.mgmt.resource.subscriptions import SubscriptionClient from azure.mgmt.policyinsights import PolicyInsightsClient Define and Assign Variables subscription_id = "exyx-exyx4e-4xyx9-axyz9c-45be63c6a8ad" # your subscription ID tenant_id = "xyzxyz-abc-cd-avc-48ebcd07d17c" # Your tenant ID client_id = "123abc-cdd-4f09-ad9f-abcdef" # Your Client ID client_secret = "wiufhuiw24874946497fff" # Your Client Secret POLICY_NAME = "KeyVaultDIAGDINEpolicy" SUBSCRIPTION_ID = "exyx-exyx4e-4xyx9-axyz9c-45be63c6a8ad" GROUP_NAME = "resourceGroupName" MANAGEMENTGROUP_ID= "abcd-123-4e7b-a446-233cvd" POLICY_ASSIGNMENT_NAME = "KVDiagDINEpolicy" Creation of objects resource_client = ResourceManagementClient( credential=ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret), subscription_id=subscription_id ) policyinsights_client = PolicyInsightsClient( credential=ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret), subscription_id=subscription_id ) policy_client = PolicyClient( credential=ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret), subscription_id=subscription_id ) Creation of Policy Definition at the Subcription Scope definitionatsubscription = policy_client.policy_definitions.create_or_update(policy_definition_name=POLICY_NAME, parameters= { "displayName": "KVDiag", "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" }, "profileName": { "type": "String", "metadata": { "displayName": "Profile name", "description": "The diagnostic settings profile name" } }, "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" } }, "azureRegions": { "type": "Array", "metadata": { "displayName": "Allowed Locations", "description": "The list of locations that can be specified when deploying resources", "strongType": "location" } }, "metricsEnabled": { "type": "String", "metadata": { "displayName": "Enable metrics", "description": "Whether to enable metrics stream to the Log Analytics workspace - True or False" }, "allowedValues": [ "True", "False" ], "defaultValue": "True" }, "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" } }, "policyRule": { "if": { "allOf": [ { "field": "type", "equals": "Microsoft.KeyVault/vaults" }, { "field": "location", "in": "[parameters('azureRegions')]" } ] }, "then": { "effect": "[parameters('effect')]", "details": { "type": "Microsoft.Insights/diagnosticSettings", "existenceCondition": { "allOf": [ { "field": "Microsoft.Insights/diagnosticSettings/logs.enabled", "equals": "[parameters('logsEnabled')]" }, { "field": "Microsoft.Insights/diagnosticSettings/metrics.enabled", "equals": "[parameters('metricsEnabled')]" }, { "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" }, "metricsEnabled": { "type": "string" }, "logsEnabled": { "type": "string" }, "profileName": { "type": "string" } }, "variables": {}, "resources": [ { "type": "Microsoft.KeyVault/vaults/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": "[parameters('metricsEnabled')]", "retentionPolicy": { "enabled": "false", "days": 0 } } ], "logs": [ { "category": "AuditEvent", "enabled": "[parameters('logsEnabled')]" } ] } } ], "outputs": {} }, "parameters": { "location": { "value": "[field('location')]" }, "resourceName": { "value": "[field('name')]" }, "logAnalytics": { "value": "[parameters('logAnalytics')]" }, "metricsEnabled": { "value": "[parameters('metricsEnabled')]" }, "logsEnabled": { "value": "[parameters('logsEnabled')]" }, "profileName": { "value": "[parameters('profileName')]" } } } } } } }}) print("Created policy definition ID : {}".format(definitionatsubscription.id)) print("Created policy definition Name : {} \n".format(definitionatsubscription.name)) print (" ********* ******** ******** ********** ******** ******* \n") Creation of Policy Definition at Management Group Scope definitionatmanagementgroup = policy_client.policy_definitions.create_or_update_at_management_group(policy_definition_name=POLICY_NAME, parameters= { "displayName": "KVDiag", "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" }, "profileName": { "type": "String", "metadata": { "displayName": "Profile name", "description": "The diagnostic settings profile name" } }, "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" } }, "azureRegions": { "type": "Array", "metadata": { "displayName": "Allowed Locations", "description": "The list of locations that can be specified when deploying resources", "strongType": "location" } }, "metricsEnabled": { "type": "String", "metadata": { "displayName": "Enable metrics", "description": "Whether to enable metrics stream to the Log Analytics workspace - True or False" }, "allowedValues": [ "True", "False" ], "defaultValue": "True" }, "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" } }, "policyRule": { "if": { "allOf": [ { "field": "type", "equals": "Microsoft.KeyVault/vaults" }, { "field": "location", "in": "[parameters('azureRegions')]" } ] }, "then": { "effect": "[parameters('effect')]", "details": { "type": "Microsoft.Insights/diagnosticSettings", "existenceCondition": { "allOf": [ { "field": "Microsoft.Insights/diagnosticSettings/logs.enabled", "equals": "[parameters('logsEnabled')]" }, { "field": "Microsoft.Insights/diagnosticSettings/metrics.enabled", "equals": "[parameters('metricsEnabled')]" }, { "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" }, "metricsEnabled": { "type": "string" }, "logsEnabled": { "type": "string" }, "profileName": { "type": "string" } }, "variables": {}, "resources": [ { "type": "Microsoft.KeyVault/vaults/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": "[parameters('metricsEnabled')]", "retentionPolicy": { "enabled": "false", "days": 0 } } ], "logs": [ { "category": "AuditEvent", "enabled": "[parameters('logsEnabled')]" } ] } } ], "outputs": {} }, "parameters": { "location": { "value": "[field('location')]" }, "resourceName": { "value": "[field('name')]" }, "logAnalytics": { "value": "[parameters('logAnalytics')]" }, "metricsEnabled": { "value": "[parameters('metricsEnabled')]" }, "logsEnabled": { "value": "[parameters('logsEnabled')]" }, "profileName": { "value": "[parameters('profileName')]" } } } } } } }},management_group_id= 'abcd-233df-4e7b-a446-2333xcvc' ) print("Created policy definition ID : {}".format(definitionatmanagementgroup.id)) print("Created policy definition Name : {} \n".format(definitionatmanagementgroup.name)) print (" ********* ******** ******** ********** ******** ******* \n") Defining Scopes for Policy Assignment scopeRG = '/subscriptions/{}/resourceGroups/{}'.format( SUBSCRIPTION_ID, GROUP_NAME ) scopeSubscription = '/subscriptions/{}'.format( SUBSCRIPTION_ID ) scopeMG = '/providers/Microsoft.Management/managementGroups/{}'.format( MANAGEMENTGROUP_ID ) Creating Policy Assignments at different Scope - Resource Group, Subscription and Management Group assignmentatRG = policy_client.policy_assignments.create( scopeRG, POLICY_ASSIGNMENT_NAME + " at RG", { 'policy_definition_id': definitionatmanagementgroup.id, "identity": {"type": "SystemAssigned"}, "location" :"eastus", 'parameters' : { "profileName": { "value": "KV_DIAG_Settings1" }, "logAnalytics": { "value": "/subscriptions/e818bd2d-e44e-4a99-a89c-45be63c6a8ad/resourcegroups/psdonotdeletessimportant/providers/microsoft.operationalinsights/workspaces/lnos-demo-1-log-sb" }, "azureRegions": { "value": ["westus"] } }, } ) print("Createed policy assignment: {}".format(assignmentatRG.id)) print("Created policy assignment: {}\n".format(assignmentatRG.name)) print (" ********* ******** ******** ********** ******** ******* \n") assignmentatsubscription = policy_client.policy_assignments.create( scopeSubscription, POLICY_ASSIGNMENT_NAME + "at Subscription", { 'policy_definition_id': definitionatsubscription.id, "identity": {"type": "SystemAssigned"}, "location" :"eastus", 'parameters' : { "profileName": { "value": "KV_DIAG_Settings2" }, "logAnalytics": { "value": "/subscriptions/e818bd2d-e44e-4a99-a89c-45be63c6a8ad/resourcegroups/psdonotdeletessimportant/providers/microsoft.operationalinsights/workspaces/lnos-demo-1-log-sb" }, "azureRegions": { "value": ["westus"] } } } ) print("Created policy assignment: {}".format(assignmentatsubscription.id)) print("Created policy assignment: {} \n".format(assignmentatsubscription.name)) print (" ********* ******** ******** ********** ******** ******* \n") assignmentatmanagementgroup = policy_client.policy_assignments.create( scopeMG, POLICY_ASSIGNMENT_NAME + "at MG", { 'policy_definition_id': definitionatmanagementgroup.id, "identity": {"type": "SystemAssigned"}, "location" :"eastus", 'parameters' : { "profileName": { "value": "KV_DIAG_Settings3" }, "logAnalytics": { "value": "/subscriptions/e818bd2d-e44e-4a99-a89c-45be63c6a8ad/resourcegroups/psdonotdeletessimportant/providers/microsoft.operationalinsights/workspaces/lnos-demo-1-log-sb" }, "azureRegions": { "value": ["westus"] } } } ) print("Created policy assignment: {}".format(assignmentatmanagementgroup.id)) print("Created policy assignment: {}\n".format(assignmentatmanagementgroup.name)) print (" ********* ******** ******** ********** ******** ******* \n") Trigger manual policy evaluation and get the resource compliance/non-compliance count : Refernce Article : https://learn.microsoft.com/en-us/powershell/module/az.policyinsights/start-azpolicycompliancescan?view=azps-10.4.1 triggerevaluation = policyinsights_client.policy_states.begin_trigger_subscription_evaluation( subscription_id='abc1233-e44e-4a99-a89c-123dfg') print("Manual policy evaluation triggered :\n{}".format(triggerevaluation.status)) policyevaluationresult = policyinsights_client.policy_states.list_query_results_for_subscription_level_policy_assignment( subscription_id='abc123-e44e-4a99-a89c-12333df', policy_states_resource="latest", policy_assignment_name= '621dc2655dd74ed68a37286d' ) for item in policyevaluationresult: print(' Resource ID : '+ item.resource_id) print(' Policy Assignment ID : '+item.policy_assignment_id) print(' Policy Assignment Scope : '+item.policy_assignment_scope) print(' Compliance State : '+item.compliance_state) print('\n') if item.compliance_state == 'Compliant': Compliant= int(Compliant +1) elif item.compliance_state == 'NonCompliant': NonCompliant = int(NonCompliant +1) else: 1==1 print('Number of Resources') print('Compliant :' + str(Compliant)) print('NonCompliant :' + str(NonCompliant)) Creation of Remediation Task at different Scopes: remediation = policyinsights_client.remediations.create_or_update_at_management_group("1233-dfdf-4e7b-a446-223233", "mymgremediation" , { "policy_assignment_id": "/providers/microsoft.management/managementgroups/6cf4d5f3-dfdf-4e7b-a446-48ebcd07d17c/providers/microsoft.authorization/policyassignments/logagents", ## "policy_definition_reference_id" : "4037797753452518688" ## (optional) Needed when we need to remediate the non-compliant resources of policy initiative assignment }) print("Create remediation:\n{}".format(remediation)) remediationRG = policyinsights_client.remediations.create_or_update_at_resource_group( "myremediationatRG", "aro-rererer", { "policy_assignment_id": "/providers/microsoft.management/managementgroups/12345-dfdf-4e7b-a446-48ebcd07d17c/providers/microsoft.authorization/policyassignments/logagents", "resource_discovery_mode" : 'ExistingNonCompliant' ## ReEvaluateCompliance - Re-evaluate the compliance state of resources and then remediate the resources found to be non-compliant. ##ExistingNonCompliant - Remediate resources that are already known to be non-compliant. }) print("Create remediation:\n{}".format(remediationRG)) remediationsubscription = policyinsights_client.remediations.create_or_update_at_subscription( "mymgremediationatsubsc" , { "policy_assignment_id": "/providers/microsoft.management/managementgroups/12333-dfdf-4e7b-a446-48ebcd07d17c/providers/microsoft.authorization/policyassignments/logagents", "resource_discovery_mode" : 'ReEvaluateCompliance' ## ReEvaluateCompliance - Re-evaluate the compliance state of resources and then remediate the resources found to be non-compliant. ##ExistingNonCompliant - Remediate resources that are already known to be non-compliant. ## "policy_definition_reference_id" : "4037797753452518688" }) print("Create remediation:\n{}".format(remediationsubscription)) Note - resource_discovery_mode is only for the policy assignments at the subscription and the resource group scope.6.3KViews5likes0CommentsMicrosoft's inconsistent implementation of tagging in Azure
We revamped our Azure resource tagging strategy several years ago and rely on them heavily for #Governance and #FinOps. We not only enforce #tags via #AzurePolicy, we also enforce tag values based on a set of permissible values for each tag. Even with that in place we experience some drift due to exclusions required in the policy definition or exemptions in the policy assignments. I won't get into why this flexibility is needed here, that's a whole separate discussion. Establishing a sound tag hygiene process becomes a vital component of your overall governance and FinOps strategies. One method we employ for tag hygiene is to surface the non-compliant resources in a #PowerBi report using an #AzureResourceGraph (ARG) query. Yes, you can do this in the Compliance section of Azure Policy as well however it lacks ease of use. For example, flipping back and forth between policies, filtering by subscriptions, surfacing other linked metadata is a cumbersome experience in the Azure Policy blade. Now onto my frustrations with how Microsoft has implemented tagging across Azure. 1. Inconsistent application of Tag case-sensitivity across tools - In Azure Policy and in the Azure portal, tag names are case-insensitive whereas tag values are case-sensitive. - In Azure Resource Graph Explorer, both tag names and tag values are case-sensitive. - Why is there inconsistency with case-sensitivity of tag names? 2. Inconsistent Tag validation across Resource Types - When deploying a Storage Account, Azure validates my tag policy before I am able to hit the create button (before it's submitted to ARM) whereas when deploying a resource like a Public IP Address, that validation only occurs after you hit the create button. This likely happens with other resource types as well. By the way, my tagging policy specifies "Indexed" for mode, so in effect it should apply to any and all resources that support tagging in Azure. - Why is does the evaluation of the tag policy differ based on the resource being deployed? 3. Inconsistent Tag UX across Resource Types - When deploying a Storage Account, the tags input is a drop-down list. However, when deploying an Azure Virtual Machine, the tags input is a textbox. Although the latter makes use of predictive text, it's still clearly a different experience. This inconsistency is found across multiple Azure resources. - Why is the tag UX different between resource types? I realize some of this is addressed or is less of a concern when using IaC but that may not be for everyone, or work in all scenarios. It would be great if Microsoft could standardize their implementation of tagging resources uniformly across the entire Azure estate. In my opinion I don't think that's a huge ask.2.4KViews4likes0CommentsChange Azure Policy assignment's system assigned managed identity location
After adding a managed identity to a policy assignment, it is possible to edit only some managed identity related settings of the policy assignment. For instance, if a system assigned managed identity has been selected and created before, its location can’t be changed and a new policy assignment needs to be created with the desired location. This article presents a custom script that creates a new policy assignment from an existing one with a system managed identity created in a specified location.5.1KViews4likes0CommentsShow user friendly message when Azure Policy does not meet compliance
We have created custom policy which checking tags existence when a user creates a new resource group. The policy works great. But we have faced unexpected behavior. When we tried to create a new resource group for test purposes (without tags) we had an uninformative error (Unexpected error while creating the resource group.). We think some people might have a misunderstanding about this message (From this message they won’t understand why they cannot create a new resource group). We investigated this issue but have not found trouble in the policy itself therefore right now we think it is an azure policy issue. Does somebody meet this kind of issue? Is there a workaround for the issue? The original feedback: https://feedback.azure.com/forums/915958-azure-governance/suggestions/36599173-show-user-friendly-message-when-azure-policy-does2.6KViews3likes1CommentAzure Policy – New Zealand Information Security Manual (NZISM) [Preview]
Whilst working with a number of organizations that needed to have compliance with https://www.nzism.gcsb.govt.nz (amongst other standards and regulations), it was a laborious path to have decent visibility against Azure resources and the NZISM compliance without customization or outside custom automation. The NZISM is measure from the https://www.protectivesecurity.govt.nz/ policy framework. The Azure Security Benchmark and ISO 27001 in https://portal.azure.com/#blade/Microsoft_Azure_Security/SecurityMenuBlade/22 supplied great general visibility towards standardized security compliance in general, but lacked the translation and mapping against NZISM requirements. The only other Azure Policy option available was to create a custom Azure Policy Set (Initiative) to map and show compliance. In-steps the new https://docs.microsoft.com/en-us/azure/governance/policy/samples/new-zealand-ism to save the day! With this being a built-in or out-of-the-box feature it means less overhead compared with the custom route. As with all things, each policy in the policy set should be reviewed prior to application to ensure it fits with expectations. The policy set should also not be used in isolation, i.e. it should be used in conjunction with other policies and features (such as the https://portal.azure.com/#blade/Microsoft_Azure_Expert/AdvisorMenuBlade/overview) to have a well rounded view. The policy set is also available on https://github.com/Azure/azure-policy/blob/master/built-in-policies/policySetDefinitions/Regulatory%20Compliance/nz_ism.json and open to contributions for any improvements or alignments needed towards the NZISM. Periodic reviews for compliance (of the policies themselves and their compliance against your resources) should also be in place as part of due diligence as always. There are a number of methods in which you can look to apply or deploy the policy set; https://docs.microsoft.com/en-us/azure/governance/policy/assign-policy-portal https://docs.microsoft.com/en-us/azure/governance/policy/assign-policy-azurecli (automation) https://docs.microsoft.com/en-us/azure/governance/policy/assign-policy-powershell (automation) https://docs.microsoft.com/en-us/azure/governance/policy/assign-policy-dotnet (automation) https://docs.microsoft.com/en-us/azure/governance/policy/assign-policy-javascript (automation) https://docs.microsoft.com/en-us/azure/governance/policy/assign-policy-python (automation) https://docs.microsoft.com/en-us/azure/governance/policy/assign-policy-rest-api (automation) https://docs.microsoft.com/en-us/azure/governance/policy/assign-policy-template (automation) https://docs.microsoft.com/en-us/azure/governance/policy/assign-policy-terraform (automation) All of the above automation tagged options you can pull into pipelines and automation vehicles (such as https://docs.microsoft.com/en-us/azure/devops/user-guide/services?view=azure-devops) to make life repeatable and easier. Even better is to include this in your Cloud Adoption Framework journey through https://docs.microsoft.com/en-us/azure/cloud-adoption-framework/govern/policy-compliance/. The Policy can also be applied at various levels; Tenant Management Group(s) Subscription(s) Resource Group(s) All that aside, how does it look in the real world? The two options that I ran through were the Azure Portal and PowerShell (AzModule) to test the waters for the policy at a subscription level scope. This is with a view to move towards subscription or management group level ARM deployments via an Azure DevOps pipeline. The application of the policy was reasonably straight forwards. Taking all of the current defaulted values from the policy (post review of each policy) set as-is means the following policy parameters need to be defined when applying: "Allowed locations" listOfAllowedLocations-e56962a6-4747-49cd-b67b-bf8b01975c4c Value = ['australiaeast','australiasoutheast'] "Allowed locations for resource groups" listOfAllowedLocations-e765b5de-1225-4ba3-bd56-1ac6695af988 Value = ['australiaeast','australiasoutheast'] "Audit Windows machines missing any of specified members in the Administrators group" MembersToInclude-30f71ea1-ac77-4f26-9fc5-2d926bbd4ba7 Value = [] "Audit Windows machines that have the specified members in the Administrators group" MembersToExclude-69bf4abd-ca1e-4cf6-8b5a-762d42e61d4f Value = [] Note: If you wish to include the Australia Central regions, these will need to be added into the values above. By default this is limited overall to Australasian and global regions. With the NZISM policy applied to the subscription, it took the usual time for it to evaluate the resources and produce it's compliance statistics. The only defaulted blocking feature of the policyset is the regional resource group and resource creations. Anything outside of the allowed regions or Global will be denied after the policy is applied. All existing resource will be allowed to exist, but show as non-compliant. This can be adjusted by setting the default action of the Policy Enforcement from Enabled (default) to Disabled. There are also optional settings to have configurable non-complaint messages (to display when a policy that is denying is blocking), but the defaulted message and appearance has enough details for the resource blocking, but the resource group blocking looks to be slightly less friendly by default at the moment: Example of Policy in “Deny” effect for disallowed locations for resource creation Example of Policy in “Deny” effect for disallowed locations for resource group creations All in all it is great built-in feature that can be very useful for those needing to comply with NZISM now with a lower amount of effort upfront. Further details are below for the two method of application used. PowerShell Note: Prior authentication and setting context to the appropriate subscription required. ################################################################# ## Register the Azure Policy Insights resource provider [One off against subscription] Register-AzResourceProvider -ProviderNamespace 'Microsoft.PolicyInsights' ###################################################################### # Assign a Policy Set/Initiative $policySetName = "d1a462af-7e6d-4901-98ac-61570b4ed22a" # New Zealand Information Security Manual $policySetAssignmentDisplayName = "New Zealand Information Security Manual" $policySetDefinition = (Get-AzPolicySetDefinition -Name $policySetName) $context=(Get-AzContext) $location='Australia East' # Region for the Managed Identity used for remediation $logAnalyticsWorkspaceId='*ADD_LA_WORKSPACE_RESOURCEID_HERE*' # LA Workspace Resource ID $parameters = [ordered]@{'MembersToInclude-30f71ea1-ac77-4f26-9fc5-2d926bbd4ba7'=('');` 'MembersToExclude-69bf4abd-ca1e-4cf6-8b5a-762d42e61d4f'=('');` 'listOfAllowedLocations-e56962a6-4747-49cd-b67b-bf8b01975c4c'=('australiaeast','australiasoutheast');` 'listOfAllowedLocations-e765b5de-1225-4ba3-bd56-1ac6695af988'=('australiaeast','australiasoutheast');` 'logAnalyticsWorkspaceId-f47b5582-33ec-4c5c-87c0-b010a6b2e917'=(''+$logAnalyticsWorkspaceId+'')} # Assign to subscription scope New-AzPolicyAssignment ` -PolicySetDefinition $policySetDefinition ` -Name $policySetName ` -AssignIdentity ` -Scope ("/subscriptions/"+$context.Subscription.Id) ` -Location $location ` -DisplayName $policySetAssignmentDisplayName ` -PolicyParameterObject $parameters ` -EnforcementMode DoNotEnforce ###################################################################### # Allow Policy System Identity access to remediate against subscription $roleDef=(Get-AzRoleDefinition -Name 'Contributor') $policySetAssignment=(Get-AzPolicyAssignment -Name $policySetName) New-AzRoleAssignment -Scope ("/subscriptions/"+$context.Subscription.Id) -ObjectId $policySetAssignment.Identity.principalId -RoleDefinitionId $roleDef.Id ###################################################################### Azure Portal Initiative/Definition Set Browse to the Azure Policy Initiative/Definition Set for the NZISM built in policy: https://portal.azure.com/#blade/Microsoft_Azure_Policy/PolicyMenuBlade/Definitions Definition ID: /providers/Microsoft.Authorization/policySetDefinitions/d1a462af-7e6d-4901-98ac-61570b4ed22a Go into the Policy by left-clicking on the policy name. Assign the policy to a scope by left-clicking the Assign button. Assign the scope as appropriate and required; Management group(s), Subscription(s), Resource Group(s). Basics Set the assignment Basics information, then left-click Next. Recommendation: Set the Policy enforcement as Disabled initial to review compliance prior to harder restrictions being put in place. Parameters Review and set all parameters for the assignment, then left-click next: Recommendation: Initially set policies to Audit (AuditIfNotExist) to review compliance prior to enforcement. Current values that should be set outside of the defaults are the following allowed locations policies: "Allowed locations" listOfAllowedLocations-e56962a6-4747-49cd-b67b-bf8b01975c4c "value": 'australiaeast','australiasoutheast' "Allowed locations for resource groups" listOfAllowedLocations-e765b5de-1225-4ba3-bd56-1ac6695af988 "value": 'australiaeast','australiasoutheast' Remediation Review and set the appropriate location for the compliance remediation managed identity to be created. Non-compliance messages Review and set either a default non-compliance message, or an individual non-compliance message per policy, then left-click next. Review + create Review the settings on the summary page and if no adjustments are required, left-click Create to set the assignment. After the creation completes, the policy will appear and start the evaluation process. This can take some time to complete. Once completed, the policy compliance can be reviewed to see what remediation is required or if appropriate, what exemptions (time based or permanent) can be approved and put in place. References Microsoft Doc’s References https://docs.microsoft.com/en-us/compliance/regulatory/offering-nz-cc-framework-nz https://docs.microsoft.com/en-us/azure/governance/policy/samples/new-zealand-ism Microsoft Github Initiative Reference https://github.com/Azure/azure-policy/blob/master/built-in-policies/policySetDefinitions/Regulatory%20Compliance/nz_ism.json NZISM https://www.nzism.gcsb.govt.nz/ Protective Security Requirements https://www.protectivesecurity.govt.nz/6.6KViews3likes0Comments