Skip to content

Commit 5d7f7f8

Browse files
author
Jill Grant
authored
Merge pull request #267111 from davidsmatlak/ds-update-policy-cli-20240223
Updates Azure Policy Az CLI quickstart
2 parents 6d967db + 8549e9e commit 5d7f7f8

File tree

1 file changed

+118
-91
lines changed

1 file changed

+118
-91
lines changed
Lines changed: 118 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -1,137 +1,164 @@
11
---
2-
title: "Quickstart: New policy assignment with Azure CLI"
3-
description: In this quickstart, you use Azure CLI to create an Azure Policy assignment to identify non-compliant resources.
4-
ms.date: 08/17/2021
2+
title: "Quickstart: Create policy assignment using Azure CLI"
3+
description: In this quickstart, you create an Azure Policy assignment to identify non-compliant resources using Azure CLI.
4+
ms.date: 02/23/2024
55
ms.topic: quickstart
6-
ms.custom: devx-track-azurecli, mode-api
6+
ms.custom: devx-track-azurecli
77
---
8-
# Quickstart: Create a policy assignment to identify non-compliant resources with Azure CLI
98

10-
The first step in understanding compliance in Azure is to identify the status of your resources.
11-
This quickstart steps you through the process of creating a policy assignment to identify virtual
12-
machines that aren't using managed disks.
9+
# Quickstart: Create a policy assignment to identify non-compliant resources using Azure CLI
1310

14-
At the end of this process, you'll successfully identify virtual machines that aren't using managed
15-
disks. They're _non-compliant_ with the policy assignment.
11+
The first step in understanding compliance in Azure is to identify the status of your resources. In this quickstart, you create a policy assignment to identify non-compliant resources using Azure CLI. The policy is assigned to a resource group and audits virtual machines that don't use managed disks. After you create the policy assignment, you identify non-compliant virtual machines.
1612

17-
Azure CLI is used to create and manage Azure resources from the command line or in scripts. This
18-
guide uses Azure CLI to create a policy assignment and to identify non-compliant resources in your
19-
Azure environment.
13+
Azure CLI is used to create and manage Azure resources from the command line or in scripts. This guide uses Azure CLI to create a policy assignment and to identify non-compliant resources in your Azure environment.
2014

2115
## Prerequisites
2216

23-
- If you don't have an Azure subscription, create a [free](https://azure.microsoft.com/free/)
24-
account before you begin.
17+
- If you don't have an Azure account, create a [free account](https://azure.microsoft.com/free/?WT.mc_id=A261C142F) before you begin.
18+
- [Azure CLI](/cli/azure/install-azure-cli).
19+
- [Visual Studio Code](https://code.visualstudio.com/).
20+
- `Microsoft.PolicyInsights` must be [registered](../../azure-resource-manager/management/resource-providers-and-types.md) in your Azure subscription. To register a resource provider, you must have permission to register resource providers. That permission is included in the Contributor and Owner roles.
21+
- A resource group with at least one virtual machine that doesn't use managed disks.
22+
23+
## Connect to Azure
24+
25+
From a Visual Studio Code terminal session, connect to Azure. If you have more than one subscription, run the commands to set context to your subscription. Replace `<subscriptionID>` with your Azure subscription ID.
2526

26-
- This quickstart requires that you run Azure CLI version 2.0.76 or later. To find the version, run
27-
`az --version`. If you need to install or upgrade, see
28-
[Install Azure CLI](/cli/azure/install-azure-cli).
27+
```azurecli
28+
az login
2929
30-
- Register the Azure Policy Insights resource provider using Azure CLI. Registering the resource
31-
provider makes sure that your subscription works with it. To register a resource provider, you
32-
must have permission to the register resource provider operation. This operation is included in
33-
the Contributor and Owner roles. Run the following command to register the resource provider:
30+
# Run these commands if you have multiple subscriptions
31+
az account list --output table
32+
az account set --subscription <subscriptionID>
33+
```
34+
35+
## Register resource provider
3436

35-
```azurecli-interactive
36-
az provider register --namespace 'Microsoft.PolicyInsights'
37-
```
37+
When a resource provider is registered, it's available to use in your Azure subscription.
3838

39-
For more information about registering and viewing resource providers, see
40-
[Resource Providers and Types](../../azure-resource-manager/management/resource-providers-and-types.md)
39+
To verify if `Microsoft.PolicyInsights` is registered, run `Get-AzResourceProvider`. The resource provider contains several resource types. If the result is `NotRegistered` run `Register-AzResourceProvider`:
4140

42-
- If you haven't already, install the [ARMClient](https://github.com/projectkudu/ARMClient). It's a
43-
tool that sends HTTP requests to Azure Resource Manager-based APIs.
41+
```azurecli
42+
az provider show \
43+
--namespace Microsoft.PolicyInsights \
44+
--query "{Provider:namespace,State:registrationState}" \
45+
--output table
4446
45-
[!INCLUDE [cloud-shell-try-it.md](../../../includes/cloud-shell-try-it.md)]
47+
az provider register --namespace Microsoft.PolicyInsights
48+
```
4649

47-
## Create a policy assignment
50+
The Azure CLI commands use a backslash (`\`) for line continuation to improve readability. For more information, go to [az provider](/cli/azure/provider).
4851

49-
In this quickstart, you create a policy assignment and assign the **Audit VMs that do not use
50-
managed disks** definition. This policy definition identifies resources that aren't compliant to the
51-
conditions set in the policy definition.
52+
## Create policy assignment
5253

53-
Run the following command to create a policy assignment:
54+
Use the following commands to create a new policy assignment for your resource group. This example uses an existing resource group that contains a virtual machine _without_ managed disks. The resource group is the scope for the policy assignment.
5455

55-
```azurecli-interactive
56-
az policy assignment create --name 'audit-vm-manageddisks' --display-name 'Audit VMs without managed disks Assignment' --scope '<scope>' --policy '<policy definition ID>'
56+
Run the following commands and replace `<resourceGroupName>` with your resource group name:
57+
58+
```azurepowershell
59+
rgid=$(az group show --resource-group <resourceGroupName> --query id --output tsv)
60+
61+
definition=$(az policy definition list \
62+
--query "[?displayName=='Audit VMs that do not use managed disks']".name \
63+
--output tsv)
5764
```
5865

59-
The preceding command uses the following information:
66+
The `rgid` variable stores the resource group ID. The `definition` variable stores the policy definition's name, which is a GUID.
6067

61-
- **Name** - The actual name of the assignment. For this example, _audit-vm-manageddisks_ was used.
62-
- **DisplayName** - Display name for the policy assignment. In this case, you're using _Audit VMs
63-
without managed disks Assignment_.
64-
- **Policy** - The policy definition ID, based on which you're using to create the assignment. In
65-
this case, it's the ID of policy definition _Audit VMs that do not use managed disks_. To get the
66-
policy definition ID, run this command:
67-
`az policy definition list --query "[?displayName=='Audit VMs that do not use managed disks']"`
68-
- **Scope** - A scope determines what resources or grouping of resources the policy assignment gets
69-
enforced on. It could range from a subscription to resource groups. Be sure to replace
70-
&lt;scope&gt; with the name of your resource group.
68+
Run the following command to create the policy assignment:
7169

72-
## Identify non-compliant resources
70+
```azurecli
71+
az policy assignment create \
72+
--name 'audit-vm-managed-disks' \
73+
--display-name 'Audit VMs without managed disks Assignment' \
74+
--scope $rgid \
75+
--policy $definition \
76+
--description 'Azure CLI policy assignment to resource group'
77+
```
7378

74-
To view the resources that aren't compliant under this new assignment, get the policy assignment ID
75-
by running the following commands:
79+
- `name` creates the policy assignment name used in the assignment's `ResourceId`.
80+
- `display-name` is the name for the policy assignment and is visible in Azure portal.
81+
- `scope` uses the `$rgid` variable to assign the policy to the resource group.
82+
- `policy` assigns the policy definition stored in the `$definition` variable.
83+
- `description` can be used to add context about the policy assignment.
84+
85+
The results of the policy assignment resemble the following example:
86+
87+
```output
88+
"description": "Azure CLI policy assignment to resource group",
89+
"displayName": "Audit VMs without managed disks Assignment",
90+
"enforcementMode": "Default",
91+
"id": "/subscriptions/{subscriptionID}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments/audit-vm-managed-disks",
92+
"identity": null,
93+
"location": null,
94+
"metadata": {
95+
"createdBy": "11111111-1111-1111-1111-111111111111",
96+
"createdOn": "2024-02-23T18:42:27.4780803Z",
97+
"updatedBy": null,
98+
"updatedOn": null
99+
},
100+
"name": "audit-vm-managed-disks",
101+
```
76102

77-
```azurecli-interactive
78-
az policy assignment list --query "[?displayName=='Audit VMs without managed disks Assignment'].id"
103+
If you want to redisplay the policy assignment information, run the following command:
104+
105+
```azurecli
106+
az policy assignment show --name "audit-vm-managed-disks" --scope $rgid
79107
```
80108

81-
For more information about policy assignment IDs, see
82-
[az policy assignment](/cli/azure/policy/assignment).
109+
For more information, go to [az policy assignment](/cli/azure/policy/assignment).
110+
111+
## Identify non-compliant resources
112+
113+
The compliance state for a new policy assignment takes a few minutes to become active and provide results about the policy's state.
114+
115+
Use the following command to identify resources that aren't compliant with the policy assignment
116+
you created:
83117

84-
Next, run the following command to get the resource IDs of the non-compliant resources that are
85-
output into a JSON file:
118+
```azurecli
119+
policyid=$(az policy assignment show \
120+
--name "audit-vm-managed-disks" \
121+
--scope $rgid \
122+
--query id \
123+
--output tsv)
86124
87-
```console
88-
armclient post "/subscriptions/<subscriptionID>/resourceGroups/<rgName>/providers/Microsoft.PolicyInsights/policyStates/latest/queryResults?api-version=2019-10-01&$filter=IsCompliant eq false and PolicyAssignmentId eq '<policyAssignmentID>'&$apply=groupby((ResourceId))" > <json file to direct the output with the resource IDs into>
125+
az policy state list --resource $policyid --filter "(isCompliant eq false)"
89126
```
90127

91-
Your results resemble the following example:
92-
93-
```json
94-
{
95-
"@odata.context": "https://management.azure.com/subscriptions/<subscriptionId>/providers/Microsoft.PolicyInsights/policyStates/$metadata#latest",
96-
"@odata.count": 3,
97-
"value": [{
98-
"@odata.id": null,
99-
"@odata.context": "https://management.azure.com/subscriptions/<subscriptionId>/providers/Microsoft.PolicyInsights/policyStates/$metadata#latest/$entity",
100-
"ResourceId": "/subscriptions/<subscriptionId>/resourcegroups/<rgname>/providers/microsoft.compute/virtualmachines/<virtualmachineId>"
101-
},
102-
{
103-
"@odata.id": null,
104-
"@odata.context": "https://management.azure.com/subscriptions/<subscriptionId>/providers/Microsoft.PolicyInsights/policyStates/$metadata#latest/$entity",
105-
"ResourceId": "/subscriptions/<subscriptionId>/resourcegroups/<rgname>/providers/microsoft.compute/virtualmachines/<virtualmachine2Id>"
106-
},
107-
{
108-
"@odata.id": null,
109-
"@odata.context": "https://management.azure.com/subscriptions/<subscriptionId>/providers/Microsoft.PolicyInsights/policyStates/$metadata#latest/$entity",
110-
"ResourceId": "/subscriptions/<subscriptionName>/resourcegroups/<rgname>/providers/microsoft.compute/virtualmachines/<virtualmachine3ID>"
111-
}
112-
113-
]
114-
}
128+
The `policyid` variable uses an expression to get the policy assignment's ID. The `filter` parameter limits the output to non-compliant resources.
129+
130+
The `az policy state list` output is verbose, but for this article the `complianceState` shows `NonCompliant`:
131+
132+
```output
133+
"complianceState": "NonCompliant",
134+
"components": null,
135+
"effectiveParameters": "",
136+
"isCompliant": false,
115137
```
116138

117-
The results are comparable to what you'd typically see listed under **Non-compliant resources** in
118-
the Azure portal view.
139+
For more information, go to [az policy state](/cli/azure/policy/state).
119140

120141
## Clean up resources
121142

122-
To remove the assignment created, use the following command:
143+
To remove the policy assignment, run the following command:
144+
145+
```azurecli
146+
az policy assignment delete --name "audit-vm-managed-disks" --scope $rgid
147+
```
148+
149+
To sign out of your Azure CLI session:
123150

124-
```azurecli-interactive
125-
az policy assignment delete --name 'audit-vm-manageddisks' --scope '/subscriptions/<subscriptionID>/<resourceGroupName>'
151+
```azurecli
152+
az logout
126153
```
127154

128155
## Next steps
129156

130157
In this quickstart, you assigned a policy definition to identify non-compliant resources in your
131158
Azure environment.
132159

133-
To learn more about assigning policies to validate that new resources are compliant, continue to the
134-
tutorial for:
160+
To learn more how to assign policies that validate if new resources are compliant, continue to the
161+
tutorial.
135162

136163
> [!div class="nextstepaction"]
137-
> [Creating and managing policies](./tutorials/create-and-manage.md)
164+
> [Tutorial: Create and manage policies to enforce compliance](./tutorials/create-and-manage.md)

0 commit comments

Comments
 (0)