Writing an Azure Policy

While there are many built-in policies available, there are many use cases in which the creation of custom policies is needed. Just like any other Azure resource, a policy is written as a JSON document. The appropriate ARM resource type is called policyDefinitions and has the following structure:

{
"name": "string",
"type": "Microsoft.Authorization/policyDefinitions",
"apiVersion": "2019-01-01",
"properties": {
"parameters": {
“location”: { …}
},
"displayName": "…",
"description": "…",
"policyRule": {
"if": {
“field”: “location”,
“equals”: “[parameters(‘location’)]”,
},
"then": {
"effect": "<audit|deny >"
}
}
}
}

The parameters object can be used to specify one or more parameters that need to be specified when assigning the policy later on. These parameters follow the same syntax and work the same as the parameters of an ARM template.

The displayName and description properties can be used to give the policy definition a meaningful name and description for later reference.

The body of the definition contains two elements, as follows:

  • The if statement is used to specify a query that selects the Azure resources that this policy should apply to. There is a specific syntax for writing complex queries in JSON that is detailed in the ARM template reference that is linked at the end of this chapter.
  • The then statement is used to describe the action that needs to be taken for any resource that matches the condition. This can be deny, that is, to automatically deny the creation of any non-compliant resource. Another approach is not to deny non-compliant deployments but rather to audit them. While denying non-compliant deployments is very straightforward in theory, there is good cause for temporarily allowing non-compliant deployments. In such cases, an audit policy can help to keep tabs on these resources. All non-compliant deployments get audit records in their Azure Activity log and can be viewed in the Azure portal, under Azure Policy in the Compliance tab. This is as follows:

After writing the policy definition, we need to create it within an Azure subscription for it to be usable. This can either be done through an ARM template or manually within the portal. From a DevOps perspective, writing policies in source control and delivering them through a pipeline as part of an ARM template is the recommended approach. In this way, Azure policies are written in the same way as the application and can be reviewed and automatically deployed to Azure as part of a DevOps pipeline.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.118.95