Quickstart: Create a policy assignment to identify non-compliant resources using JavaScript

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 virtual machines that aren't using managed disks. When complete, you'll identify virtual machines that are non-compliant.

The JavaScript library is used to manage Azure resources from the command line or in scripts. This guide explains how to use JavaScript library to create a policy assignment.

Prerequisites

  • Azure subscription: If you don't have an Azure subscription, create a free account before you begin.

  • Node.js: Node.js version 12 or higher is required.

Use Azure Cloud Shell

Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. You can use either Bash or PowerShell with Cloud Shell to work with Azure services. You can use the Cloud Shell preinstalled commands to run the code in this article without having to install anything on your local environment.

To start Azure Cloud Shell:

Option Example/Link
Select Try It in the upper-right corner of a code block. Selecting Try It doesn't automatically copy the code to Cloud Shell. Example of Try It for Azure Cloud Shell
Go to https://shell.azure.com, or select the Launch Cloud Shell button to open Cloud Shell in your browser. Launch Cloud Shell in a new window
Select the Cloud Shell button on the menu bar at the upper right in the Azure portal. Cloud Shell button in the Azure portal

To run the code in this article in Azure Cloud Shell:

  1. Start Cloud Shell.

  2. Select the Copy button on a code block to copy the code.

  3. Paste the code into the Cloud Shell session by selecting Ctrl+Shift+V on Windows and Linux or by selecting Cmd+Shift+V on macOS.

  4. Select Enter to run the code.

Add the Policy libraries

To enable JavaScript to work with Azure Policy, the libraries must be added. These libraries work wherever JavaScript can be used, including bash on Windows 10.

  1. Set up a new Node.js project by running the following command.

    npm init -y
    
  2. Add a reference to the yargs library.

    npm install yargs
    
  3. Add a reference to the Azure Policy libraries.

    # arm-policy is for working with Azure Policy objects such as definitions and assignments
    npm install @azure/arm-policy
    
    # arm-policyinsights is for working with Azure Policy compliance data such as events and states
    npm install @azure/arm-policyinsights
    
  4. Add a reference to the Azure authentication library.

    npm install @azure/ms-rest-nodeauth
    

    Note

    Verify in package.json @azure/arm-policy is version 3.1.0 or higher, @azure/arm-policyinsights is version 3.2.0 or higher, and @azure/ms-rest-nodeauth is version 3.0.5 or higher.

Create a policy assignment

In this quickstart, you create a policy assignment and assign the Audit VMs that do not use managed disks (06a78e20-9358-41c9-923c-fb736d382a4d) definition. This policy definition identifies resources that aren't compliant to the conditions set in the policy definition.

  1. Create a new file named policyAssignment.js and enter the following code.

    const argv = require("yargs").argv;
    const authenticator = require("@azure/ms-rest-nodeauth");
    const policyObjects = require("@azure/arm-policy");
    
    if (argv.subID && argv.name && argv.displayName && argv.policyDefID && argv.scope && argv.description) {
    
        const createAssignment = async () => {
            const credentials = await authenticator.interactiveLogin();
            const client = new policyObjects.PolicyClient(credentials, argv.subID);
            const assignments = new policyObjects.PolicyAssignments(client);
    
            const result = await assignments.create(
                argv.scope,
                argv.name,
                {
                    displayName: argv.displayName,
                    policyDefinitionId: argv.policyDefID,
                    description: argv.description
                }
            );
            console.log(result);
        };
    
        createAssignment();
    }
    
  2. Enter the following command in the terminal:

    node policyAssignment.js `
       --subID "{subscriptionId}" `
       --name "audit-vm-manageddisks" `
       --displayName "Audit VMs without managed disks Assignment" `
       --policyDefID "/providers/Microsoft.Authorization/policyDefinitions/06a78e20-9358-41c9-923c-fb736d382a4d" `
       --description "Shows all virtual machines not using managed disks" `
       --scope "{scope}"
    

The preceding commands use the following information:

  • subID - The subscription ID for authentication context. Be sure to replace {subscriptionId} with your subscription.
  • name - The unique name for the policy assignment object. The example above uses audit-vm-manageddisks.
  • displayName - Display name for the policy assignment. In this case, you're using Audit VMs without managed disks Assignment.
  • policyDefID - The policy definition path, based on which you're using to create the assignment. In this case, it's the ID of policy definition Audit VMs that do not use managed disks.
  • description - A deeper explanation of what the policy does or why it's assigned to this scope.
  • scope - A scope determines what resources or grouping of resources the policy assignment gets enforced on. It could range from a management group to an individual resource. Be sure to replace {scope} with one of the following patterns:
    • Management group: /providers/Microsoft.Management/managementGroups/{managementGroup}
    • Subscription: /subscriptions/{subscriptionId}
    • Resource group: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}
    • Resource: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]

You're now ready to identify non-compliant resources to understand the compliance state of your environment.

Identify non-compliant resources

Now that your policy assignment is created, you can identify resources that aren't compliant.

  1. Create a new file named policyState.js and enter the following code.

    const argv = require("yargs").argv;
    const authenticator = require("@azure/ms-rest-nodeauth");
    const policyInsights = require("@azure/arm-policyinsights");
    
    if (argv.subID && argv.name) {
    
        const getStates = async () => {
    
            const credentials = await authenticator.interactiveLogin();
            const client = new policyInsights.PolicyInsightsClient(credentials);
            const policyStates = new policyInsights.PolicyStates(client);
            const result = await policyStates.listQueryResultsForSubscription(
                "latest",
                argv.subID,
                {
                    queryOptions: {
                        filter: "IsCompliant eq false and PolicyAssignmentId eq '" + argv.name + "'",
                        apply: "groupby((ResourceId))"
                    }
                }
            );
            console.log(result);
        };
    
        getStates();
    }
    
  2. Enter the following command in the terminal:

    node policyState.js --subID "{subscriptionId}" --name "audit-vm-manageddisks"
    

Replace {subscriptionId} with the subscription you want to see the compliance results for the policy assignment named 'audit-vm-manageddisks' that we created in the previous steps. For a list of other scopes and ways to summarize the data, see PolicyStates* methods.

Your results resemble the following example:

{
    'additional_properties': {
        '@odata.nextLink': None
    },
    'odatacontext': 'https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/$metadata#latest',
    'odatacount': 12,
    'value': [{data}]
}

The results match what you see in the Resource compliance tab of a policy assignment in the Azure portal view.

Clean up resources

  • Delete the policy assignment Audit VMs without managed disks Assignment through the portal. The policy definition is a built-in, so there's no definition to remove.

  • If you wish to remove the installed libraries from your application, run the following command.

    npm uninstall @azure/arm-policy @azure/arm-policyinsights @azure/ms-rest-nodeauth yargs
    

Next steps

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

To learn more about assigning policy definitions to validate that new resources are compliant, continue to the tutorial for: