Manage Azure Policy using PowerShell or Azure CLI

Azure Policy helps to enforce organizational standards and to assess compliance at-scale.
A policy definition expresses what to evaluate and what action to take. The policy definition itself is represented as a JSON file - you can use one of the pre-defined definitions in the portal or create your own (either modifying an existing one or starting from scratch).
Each policy definition in Azure Policy has a single effect. That effect determines what happens when the associated policy rule is matched. Below are the list:

Deny
The resource creation/update fails due to policy.

Disabled
The policy rule is ignored (disabled). Often used for testing.

Append
Adds additional parameters/fields to the requested resource during creation or update. A common example is adding tags on resources such as Cost Center or specifying allowed IPs for a storage resource.

Audit, AuditIfNotExists
Creates a warning event in the activity log when evaluating a non-compliant resource, but it doesn't stop the request.

DeployIfNotExists
Executes a template deployment when a specific condition is met. For example, if SQL encryption is enabled on a database, then it can run a template after the DB is created to set it up a specific way.

To Manage Policy or create custom policy follow below Powershell or CLI commands

# First Register the resource provider if it's not already registered with PolicyInsights extension
Register-AzResourceProvider -ProviderNamespace 'Microsoft.PolicyInsights'

# Same Using Azure CLI
az provider register --namespace 'Microsoft.PolicyInsights'

# Get a reference to the resource group that will be the scope of the assignment
$rg = Get-AzResourceGroup -Name '<resourceGroupName>'

# Get a reference to the built-in policy definition that will be assigned
$definition = Get-AzPolicyDefinition | Where-Object { $_.Properties.DisplayName -eq 'Audit VMs that do not use managed disks' }

# Create the policy assignment with the built-in definition against your resource group
New-AzPolicyAssignment -Name 'audit-vm-manageddisks' -DisplayName 'Audit VMs without managed disks Assignment' -Scope $rg.ResourceId -PolicyDefinition $definition

az policy assignment create --name 'audit-vm-manageddisks' --display-name 'Audit VMs without managed disks Assignment' --scope '<scope>' --policy '<policy definition ID>'

# Get the resources in your resource group that are non-compliant to the policy assignment
Get-AzPolicyState -ResourceGroupName $rg.ResourceGroupName -PolicyAssignmentName 'audit-vm-manageddisks' -Filter 'IsCompliant eq false'

#other way run the following command to get the resource IDs of the non-compliant resources that are output into a JSON file:
$policyAssignment = Get-AzPolicyAssignment | Where-Object { $_.Properties.DisplayName -eq 'Audit VMs without managed disks Assignment' }
$policyAssignment.PolicyAssignmentId

armclient post "/subscriptions/<subscriptionID>/resourceGroups/<rgName>/providers/Microsoft.PolicyInsights/policyStates/latest/queryResults?api-version=2017-12-12-preview&$filter=IsCompliant eq false and PolicyAssignmentId eq '<policyAssignmentID>'&$apply=groupby((ResourceId))" > <json file to direct the output with the resource IDs into>

# Removes the policy assignment
Remove-AzPolicyAssignment -Name 'audit-vm-manageddisks' -Scope '/subscriptions/<subscriptionID>/resourceGroups/<resourceGroupName>'
az policy assignment delete --name 'audit-vm-manageddisks' --scope '/subscriptions/<subscriptionID>/<resourceGroupName>'

#To create a policy definition from a file, pass the path to the file. For an external file or local file or inline rule
$definition = New-AzPolicyDefinition -Name 'denyCoolTiering' -DisplayName 'Deny cool access tiering for storage' -Policy 'https://raw.githubusercontent.com/Azure/azure-policy-samples/master/samples/Storage/storage-account-access-tier/azurepolicy.rules.json'

$definition = New-AzPolicyDefinition -Name 'denyCoolTiering' -Description 'Deny cool access tiering for storage' -Policy 'c:\policies\coolAccessTier.json'
$definition = New-AzPolicyDefinition -Name 'denyCoolTiering' -Description 'Deny cool access tiering for storage' -Policy '{
    "if": {
        "allOf": [{
                "field": "type",
                "equals": "Microsoft.Storage/storageAccounts"
            },
            {
                "field": "kind",
                "equals": "BlobStorage"
            },
            {
                "field": "Microsoft.Storage/storageAccounts/accessTier",
                "equals": "cool"
            }
        ]
    },
    "then": {
        "effect": "deny"
    }
}'

az policy definition create --name 'denyCoolTiering' --description 'Deny cool access tiering for storage' --rules 'c:\policies\coolAccessTier.json'

#The following example creates a policy definition that includes parameters:
$policy = '{
    "if": {
        "allOf": [{
                "field": "type",
                "equals": "Microsoft.Storage/storageAccounts"
            },
            {
                "not": {
                    "field": "location",
                    "in": "[parameters(''allowedLocations'')]"
                }
            }
        ]
    },
    "then": {
        "effect": "Deny"
    }
}'

$parameters = '{
    "allowedLocations": {
        "type": "array",
        "metadata": {
            "description": "The list of locations that can be specified when deploying storage accounts.",
            "strongType": "location",
            "displayName": "Allowed locations"
        }
    }
}'

$definition = New-AzPolicyDefinition -Name 'storageLocations' -Description 'Policy to specify locations for storage accounts.' -Policy $policy -Parameter $parameters

#View policy definitions, each policy output format is diffrent in Powershell and ACLI (JSON format)
Get-AzPolicyDefinition | ? { $_.Properties.displayName -eq 'Audit unrestricted network access to storage accounts' }

# Name               : e56962a6-4747-49cd
# ResourceId         : /providers/Microsoft.Authorization/policyDefinitions/e56962a6-4747-49cd
# ResourceName       : e56962a6-4747-49cd
# ResourceType       : Microsoft.Authorization/policyDefinitions
# Properties         : @{displayName=Allowed locations; policyType=BuiltIn; description=This policy enables you to restrict the locations your organization can specify when deploying resources. Use to enforce your geo-compliance requirements.; parameters=; policyRule=}
# PolicyDefinitionId : /providers/Microsoft.Authorization/policyDefinitions/e56962a6-4747-49cd

az policy definition list
{
    "description": "This policy enables you to restrict the locations your organization can specify when deploying resources. Use to enforce your geo-compliance requirements.",
    "displayName": "Allowed locations",
    "id": "/providers/Microsoft.Authorization/policyDefinitions/e56962a6-4747-49cd",
    "name": "e56962a6-4747-49cd",
    "policyRule": {
        "if": {
            "not": {
                "field": "location",
                "in": "[parameters('listOfAllowedLocations')]"
            }
        },
        "then": {
            "effect": "Deny"
        }
    },
    "policyType": "BuiltIn"
}

We can use the applied policy definition to identify resources that aren't compliant with the policy assignment through the Azure portal

Post a Comment

Thanks for your comment !
I will review your this and will respond you as soon as possible.