快速入门:使用 JavaScript 创建策略分配以识别不合规的资源Quickstart: Create a policy assignment to identify non-compliant resources using JavaScript

若要了解 Azure 中的符合性,第一步是确定资源的状态。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.

JavaScript 库用于从命令行或脚本管理 Azure 资源。The JavaScript library is used to manage Azure resources from the command line or in scripts. 本指南介绍如何使用 JavaScript 库来创建策略分配。This guide explains how to use JavaScript library to create a policy assignment.

先决条件Prerequisites

  • Azure 订阅:如果没有 Azure 订阅,请在开始之前创建一个 免费帐户。Azure subscription: If you don't have an Azure subscription, create a free account before you begin.

  • Node.js:需要 Node.js 版本 12 或更高版本。Node.js: Node.js version 12 or higher is required.

添加 Policy 库Add the Policy libraries

要使 JavaScript 能够使用 Azure Policy,必须添加这些库。To enable JavaScript to work with Azure Policy, the libraries must be added. 这些库适用于可使用 JavaScript 的任何环境,包括 Windows 10 上的 BashThese libraries work wherever JavaScript can be used, including bash on Windows 10.

  1. 运行以下命令,设置新的 Node.js 项目。Set up a new Node.js project by running the following command.

    npm init -y
    
  2. 添加对 yargs 库的引用。Add a reference to the yargs library.

    npm install yargs
    
  3. 添加对 Azure Policy 库的引用。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. 添加对 Azure 身份验证库的引用。Add a reference to the Azure authentication library.

    npm install @azure/ms-rest-nodeauth
    

    备注

    在 package.json 中验证 @azure/arm-policy 是否为版本 3.1.0 或更高版本、@azure/arm-policyinsights 是否为版本 3.2.0 或更高版本,以及 @azure/ms-rest-nodeauth 是否为版本 3.0.5 或更高版本 。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

本快速入门将创建一个策略分配,并分配“审核未使用托管磁盘的 VM”(06a78e20-9358-41c9-923c-fb736d382a4d) 定义。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. 新建一个名为 policyAssignment.js 的文件,并输入以下代码。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 - 身份验证上下文的订阅 ID。subID - The subscription ID for authentication context. 请确保将 {subscriptionId} 替换为你的订阅。Be sure to replace {subscriptionId} with your subscription.
  • name - 策略分配对象的唯一名称。name - The unique name for the policy assignment object. 上面的示例使用 audit-vm-manageddisks。The example above uses audit-vm-manageddisks.
  • displayName - 策略分配的显示名称。displayName - Display name for the policy assignment. 本例使用了“审核未使用托管磁盘分配的虚拟机” 。In this case, you're using Audit VMs without managed disks Assignment.
  • policyDefID - 策略定义路径,用作创建分配的依据。policyDefID – The policy definition path, based on which you're using to create the assignment. 在本例中,它为策略定义“审核未使用托管磁盘的 VM”的 ID 。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. 请确保将 {scope} 替换为以下某个模式:Be sure to replace {scope} with one of the following patterns:
    • 管理组:/providers/Microsoft.Management/managementGroups/{managementGroup}Management group: /providers/Microsoft.Management/managementGroups/{managementGroup}
    • 订阅:/subscriptions/{subscriptionId}Subscription: /subscriptions/{subscriptionId}
    • 资源组:/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}Resource group: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}
    • 资源:/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]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. 新建一个名为 policyState.js 的文件,并输入以下代码。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"
    

{subscriptionId} 替换为你要在其中查看前面步骤中已创建的名为“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. 有关用于汇总数据的其他作用域和方法的列表,请参阅PolicyStates* 方法。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.chinacloudapi.cn/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/$metadata#latest',
    'odatacount': 12,
    'value': [{data}]
}

结果与 Azure 门户视图中策略分配的“资源符合性” 选项卡中显示的内容相匹配。The results match what you see in the Resource compliance tab of a policy assignment in the Azure portal view.

清理资源Clean up resources

  • 通过门户删除策略分配“审核不带托管磁盘分配的 VM”。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

本快速入门已分配一个策略定义用于识别 Azure 环境中的不合规资源。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: