如何创建适用于 Windows 的来宾配置策略How to create Guest Configuration policies for Windows

创建自定义策略定义之前,最好参阅 Azure Policy 来宾配置页中的概念性概述信息。Before creating custom policy definitions, it's a good idea to read the conceptual overview information at the page Azure Policy Guest Configuration.

若要了解如何创建适用于 Linux 的来宾配置策略,请参阅如何创建适用于 Linux 的来宾配置策略To learn about creating Guest Configuration policies for Linux, see the page How to create Guest Configuration policies for Linux

审核 Windows 时,来宾配置使用 Desired State Configuration (DSC) 资源模块创建配置文件。When auditing Windows, Guest Configuration uses a Desired State Configuration (DSC) resource module to create the configuration file. DSC 配置定义了计算机应处于的条件。The DSC configuration defines the condition that the machine should be in. 如果配置评估失败,则会触发策略效果 auditIfNotExists,并将计算机视为不符合。If the evaluation of the configuration fails, the policy effect auditIfNotExists is triggered and the machine is considered non-compliant.

Azure Policy 来宾配置只能用于审核计算机内部的设置。Azure Policy Guest Configuration can only be used to audit settings inside machines. 还不能修正计算机内部的设置。Remediation of settings inside machines isn't yet available.

请执行以下操作来创建你自己的配置,用于验证 Azure 或非 Azure 计算机的状态。Use the following actions to create your own configuration for validating the state of an Azure or non-Azure machine.

重要

Azure 中国环境中具有来宾配置的自定义策略定义是一项预览功能。Custom policy definitions with Guest Configuration in the Azure China environments is a Preview feature.

必须有来宾配置扩展,才能在 Azure 虚拟机中执行审核。The Guest Configuration extension is required to perform audits in Azure virtual machines. 若要在所有 Windows 计算机上大规模部署该扩展,请分配以下策略定义:Deploy prerequisites to enable Guest Configuration Policy on Windows VMsTo deploy the extension at scale across all Windows machines, assign the following policy definitions: Deploy prerequisites to enable Guest Configuration Policy on Windows VMs

不要在自定义内容包中使用机密或保密信息。Don't use secrets or confidential information in custom content packages.

安装 PowerShell 模块Install the PowerShell module

来宾配置模块自动执行创建自定义内容的过程,包括:The Guest Configuration module automates the process of creating custom content including:

  • 创建来宾配置内容项目 (.zip)Creating a Guest Configuration content artifact (.zip)
  • 自动测试项目Automated testing of the artifact
  • 创建策略定义Creating a policy definition
  • 发布策略Publishing the policy

该模块可以安装在运行 Windows、macOS 或 Linux 并装有 PowerShell 6.2 或更高版本的计算机本地,或者与 Azure PowerShell Core Docker 映像一起安装。The module can be installed on a machine running Windows, macOS, or Linux with PowerShell 6.2 or later running locally, or with the Azure PowerShell Core Docker image.

备注

Linux 上尚不支持编译配置。Compilation of configurations is not yet supported on Linux.

基本要求Base requirements

可以安装模块的操作系统:Operating Systems where the module can be installed:

  • LinuxLinux
  • macOSmacOS
  • WindowsWindows

来宾配置资源模块需要以下软件:The Guest Configuration resource module requires the following software:

  • PowerShell 6.2 或更高版本。PowerShell 6.2 or later. 若尚未安装,请遵循这些说明If it isn't yet installed, follow these instructions.

  • Azure PowerShell 1.5.0 或更高版本。Azure PowerShell 1.5.0 or higher. 若尚未安装,请遵循这些说明If it isn't yet installed, follow these instructions.

    • 只有 Az 模块“Az.Accounts”和“Az.Resources”是必需的。Only the Az modules 'Az.Accounts' and 'Az.Resources' are required.

安装模块Install the module

若要在 PowerShell 中安装 GuestConfiguration 模块,请执行以下操作:To install the GuestConfiguration module in PowerShell:

  1. 在 PowerShell 提示符下,运行以下命令:From a PowerShell prompt, run the following command:

    # Install the Guest Configuration DSC resource module from PowerShell Gallery
    Install-Module -Name GuestConfiguration
    
  2. 验证模块是否已导入:Validate that the module has been imported:

    # Get a list of commands for the imported GuestConfiguration module
    Get-Command -Module 'GuestConfiguration'
    

适用于 Windows 的来宾配置项目和策略Guest Configuration artifacts and policy for Windows

来宾配置使用 PowerShell Desired State Configuration 作为语言抽象来编写要在 Windows 中审核的内容。Guest Configuration uses PowerShell Desired State Configuration as a language abstraction for writing what to audit in Windows. 代理会加载 PowerShell 6.2 的独立实例,因此,在 Windows PowerShell 5.1 中使用 PowerShell DSC 不会产生冲突,并且不要求预先安装 PowerShell 6.2 或更高版本。The agent loads a standalone instance of PowerShell 6.2, so there isn't conflict with usage of PowerShell DSC in Windows PowerShell 5.1, and there's no requirement to pre-install PowerShell 6.2 or later.

有关 DSC 概念和术语的概述,请参阅 PowerShell DSC 概述For an overview of DSC concepts and terminology, see PowerShell DSC Overview.

来宾配置模块与 Windows PowerShell DSC 模块的区别How Guest Configuration modules differ from Windows PowerShell DSC modules

当“来宾配置”审核计算机时,事件的顺序与在 Windows PowerShell DSC 中不同。When Guest Configuration audits a machine the sequence of events is different than in Windows PowerShell DSC.

  1. 代理首先运行 Test-TargetResource 以确定配置是否处于正确状态。The agent first runs Test-TargetResource to determine if the configuration is in the correct state.
  2. 该函数返回的布尔值确定来宾分配的 Azure 资源管理器状态是合规还是不合规。The boolean value returned by the function determines if the Azure Resource Manager status for the Guest Assignment should be Compliant/Not-Compliant.
  3. 提供程序运行 Get-TargetResource 以返回每个设置的当前状态,因此,会获得有关计算机为何不合规的详细信息,以及用于确认当前状态是否合规的详细信息。The provider runs Get-TargetResource to return the current state of each setting so details are available both about why a machine isn't compliant and to confirm that the current state is compliant.

Azure 策略中将值传递给“来宾配置”分配信息的参数必须为字符串类型。Parameters in Azure Policy that pass values to Guest Configuration assignments must be string type. 即使 DSC 资源支持数组,也无法通过参数传递数组。It isn't possible to pass arrays through parameters, even if the DSC resource supports arrays.

Get-TargetResource 要求Get-TargetResource requirements

函数 Get-TargetResource 对来宾配置具有特殊要求,而 Windows Desired State Configuration 不需要满足这些要求。The function Get-TargetResource has special requirements for Guest Configuration that haven't been needed for Windows Desired State Configuration.

  • 返回的哈希表必须包含名为 Reasons 的属性。The hashtable that is returned must include a property named Reasons.
  • Reasons 属性必须是数组。The Reasons property must be an array.
  • 数组中的每个项都应是一个哈希表,其中包含名为 Code 和 Phrase 的键。Each item in the array should be a hashtable with keys named Code and Phrase.

当计算机不合规时,服务使用 Reasons 属性来标准化信息的呈现方式。The Reasons property is used by the service to standardize how information is presented when a machine is out of compliance. 可将 Reasons 中的每个项视为资源不合规的一个“原因”。You can think of each item in Reasons as a "reason" that the resource isn't compliant. 该属性之所以是数组,是因为资源可能出于多种原因而不合规。The property is an array because a resource could be out of compliance for more than one reason.

服务需要 Code 和 Phrase 属性。The properties Code and Phrase are expected by the service. 创作自定义资源时,需将要显示为资源不合规原因的文本(通常为 stdout)设置为 Phrase 的值。When authoring a custom resource, set the text (typically stdout) you would like to show as the reason the resource isn't compliant as the value for Phrase. Code 具有特定格式设置要求,因此报告可以清楚地显示有关用于进行审核的资源的信息。Code has specific formatting requirements so reporting can clearly display information about the resource used to do the audit. 此解决方案使来宾配置可扩展。This solution makes Guest Configuration extensible. 只要输出可以作为 Phrase 属性的字符串值返回,便可以运行任何命令。Any command could be run as long as the output can be returned as a string value for the Phrase property.

  • Code(字符串):资源的名称,重复该名称,后接一个不包含空格的短名称(作为原因标识符)。Code (string): The name of the resource, repeated, and then a short name with no spaces as an identifier for the reason. 这三个值应以冒号分隔,且不包含空格。These three values should be colon-delimited with no spaces.
    • 例如 registry:registry:keynotpresentAn example would be registry:registry:keynotpresent
  • Phrase(字符串):用户可读的文本,用于解释设置不合规的原因。Phrase (string): Human-readable text to explain why the setting isn't compliant.
    • 例如 The registry key $key is not present on the machine.An example would be The registry key $key is not present on the machine.
$reasons = @()
$reasons += @{
  Code = 'Name:Name:ReasonIdentifer'
  Phrase = 'Explain why the setting is not compliant'
}
return @{
    reasons = $reasons
}

必须将 Reasons 属性添加到嵌入类形式的资源的架构 MOF。The Reasons property must be added to the schema MOF for the resource as an embedded class.

[ClassVersion("1.0.0.0")] 
class Reason
{
    [Read] String Phrase;
    [Read] String Code;
};

[ClassVersion("1.0.0.0"), FriendlyName("ResourceName")]
class ResourceName : OMI_BaseResource
{
    [Key, Description("Example description")] String Example;
    [Read, EmbeddedInstance("Reason")] String Reasons[];
};

如果资源具有所需的属性,还必须通过 Get-TargetResourcereasons 类来返回这些属性。If the resource has required properties, those properties must also be returned by Get-TargetResource in parallel with the reasons class. 如果未包括 reasons,则该服务将包括“全部捕获”行为,该行为将输入到 Get-TargetResource 的值与 Get-TargetResource 返回的值进行比较,并将详细的比较结果作为 reasons 提供。If reasons isn't included, the service includes a "catch-all" behavior that compares the values input to Get-TargetResource and the values returned by Get-TargetResource, and provides a detailed comparison as reasons.

配置要求Configuration requirements

自定义配置的名称必须在所有位置都保持一致。The name of the custom configuration must be consistent everywhere. 内容包的 .zip 文件名称、MOF 文件中的配置名称,以及 Azure 资源管理器模板 (ARM template) 中的来宾分配名称必须相同。The name of the .zip file for the content package, the configuration name in the MOF file, and the guest assignment name in the Azure Resource Manager template (ARM template), must be the same.

策略要求Policy requirements

策略定义 metadata 部分必须包括来宾配置服务的两个属性,以自动预配和报告来宾配置分配。The policy definition metadata section must include two properties for the Guest Configuration service to automate provisioning and reporting of Guest Configuration assignments. category 属性必须设置为“来宾配置”,并且名为 Guest Configuration 的部分必须包含有关来宾配置分配的信息。The category property must be set to "Guest Configuration" and a section named Guest Configuration must contain information about the Guest Configuration assignment. New-GuestConfigurationPolicy cmdlet 会自动创建此文本。The New-GuestConfigurationPolicy cmdlet creates this text automatically. 请参阅此页上的分步说明。See the step-by-step instructions on this page.

以下示例演示了 metadata 部分。The following example demonstrates the metadata section.

    "metadata": {
      "category": "Guest Configuration",
      "guestConfiguration": {
        "name": "test",
        "version": "1.0.0",
        "contentType": "Custom",
        "contentUri": "CUSTOM-URI-HERE",
        "contentHash": "CUSTOM-HASH-VALUE-HERE",
        "configurationParameter": {}
      }
    },

搭建来宾配置项目Scaffolding a Guest Configuration project

想要加速入门过程并从示例代码开始工作的开发人员可以安装名为“来宾配置项目”的社区项目。Developers who would like to accelerate the process of getting started and work from sample code can install a community project named Guest Configuration Project. 该项目将安装 Plaster PowerShell 模块的模板。The project installs a template for the Plaster PowerShell module. 此工具可用于搭建项目(包括工作配置和示例资源)以及一组 Pester 测试来验证项目。This tool can be used to scaffold a project including a working configuration and sample resource, and a set of Pester tests to validate the project. 该模板还包含适用于 Visual Studio Code 的任务运行程序,用于自动生成和验证来宾配置包。The template also includes task runners for Visual Studio Code to automate building and validating the Guest Configuration package. 有关详细信息,请参阅 GitHub 项目来宾配置项目For more information, see the GitHub project Guest Configuration Project.

有关一般情况下使用配置的详细信息,请参阅编写、编译和应用配置For more information about working with configurations in general, see Write, Compile, and Apply a Configuration.

来宾配置项目的预期内容Expected contents of a Guest Configuration artifact

来宾配置使用已完成的包来创建 Azure Policy 定义。The completed package is used by Guest Configuration to create the Azure Policy definitions. 包中包含:The package consists of:

  • 作为 MOF 的已编译 DSC 配置The compiled DSC configuration as a MOF
  • 模块文件夹Modules folder
    • GuestConfiguration 模块GuestConfiguration module
    • DscNativeResources 模块DscNativeResources module
    • (Windows) MOF 所需的 DSC 资源模块(Windows) DSC resource modules required by the MOF

PowerShell cmdlet 可帮助创建包。PowerShell cmdlets assist in creating the package. 不需要根级别文件夹或版本文件夹。No root level folder or version folder is required. 包格式必须是 .zip 文件,未压缩时总大小不能超过 100 MB。The package format must be a .zip file and can't exceed a total size of 100 MB when uncompressed.

存储来宾配置项目Storing Guest Configuration artifacts

.zip 包必须存储在可由托管虚拟机访问的位置。The .zip package must be stored in a location that is accessible by the managed virtual machines. 示例包括 GitHub 存储库、Azure 存储库或 Azure 存储。Examples include GitHub repositories, an Azure Repo, or Azure storage. 如果你不想使包公开,则可以在 URL 中包含 SAS 令牌If you prefer to not make the package public, you can include a SAS token in the URL. 还可以为专用网络中的计算机实现服务终结点,不过此配置仅适用于访问包,而不适用于与服务通信。You could also implement service endpoint for machines in a private network, although this configuration applies only to accessing the package and not communicating with the service.

逐步创建适用于 Windows 的自定义来宾配置审核策略Step by step, creating a custom Guest Configuration audit policy for Windows

创建 DSC 配置以审核设置。Create a DSC configuration to audit settings. 下面的 PowerShell 脚本示例创建一个名为 AuditBitLocker 的配置,导入 PsDscResources 资源模块,并使用 Service 资源审核正在运行的服务。The following PowerShell script example creates a configuration named AuditBitLocker, imports the PsDscResources resource module, and uses the Service resource to audit for a running service. 可以从 Windows 或 macOS 计算机执行配置脚本。The configuration script can be executed from a Windows or macOS machine.

# Add PSDscResources module to environment
Install-Module 'PSDscResources'

# Define the DSC configuration and import GuestConfiguration
Configuration AuditBitLocker
{
    Import-DscResource -ModuleName 'PSDscResources'

    Node AuditBitlocker {
      Service 'Ensure BitLocker service is present and running'
      {
          Name = 'BDESVC'
          Ensure = 'Present'
          State = 'Running'
      }
    }
}

# Compile the configuration to create the MOF files
AuditBitLocker

在 PowerShell 终端中运行此脚本,或在项目文件夹中使用名称 config.ps1 保存此文件。Run this script in a PowerShell terminal or save this file with name config.ps1 in the project folder. 通过在终端中执行 ./config.ps1,在 PowerShell 中运行它。Run it in PowerShell by executing ./config.ps1 in the terminal. 随即将创建新 mof 文件。A new mof file is created.

从技术上讲,Node AuditBitlocker 命令不是必需的,但它会生成一个名为 AuditBitlocker.mof(而不是默认的 localhost.mof)的文件。The Node AuditBitlocker command isn't technically required but it produces a file named AuditBitlocker.mof rather than the default, localhost.mof. 让 .mof 文件名遵循配置,可以在大规模操作时轻松地组织许多文件。Having the .mof file name follow the configuration makes it easy to organize many files when operating at scale.

编译 MOF 后,支持文件必须打包在一起。Once the MOF is compiled, the supporting files must be packaged together. 来宾配置使用已完成的包来创建 Azure Policy 定义。The completed package is used by Guest Configuration to create the Azure Policy definitions.

New-GuestConfigurationPackage cmdlet 创建包。The New-GuestConfigurationPackage cmdlet creates the package. 配置所需的模块必须在 $Env:PSModulePath 中提供。Modules that are needed by the configuration must be in available in $Env:PSModulePath. 创建 Windows 内容时 New-GuestConfigurationPackage cmdlet 的参数:Parameters of the New-GuestConfigurationPackage cmdlet when creating Windows content:

  • Name:来宾配置包名称。Name: Guest Configuration package name.
  • 配置:已编译 DSC 配置文档完整路径。Configuration: Compiled DSC configuration document full path.
  • 路径:输出文件夹路径。Path: Output folder path. 此参数是可选的。This parameter is optional. 如果未指定,则在当前目录中创建包。If not specified, the package is created in current directory.

运行下面的命令,以使用上一步中给出的配置来创建包:Run the following command to create a package using the configuration given in the previous step:

New-GuestConfigurationPackage `
  -Name 'AuditBitlocker' `
  -Configuration './AuditBitlocker/AuditBitlocker.mof'

创建配置包之后、将其发布到 Azure 之前,可以从工作站或持续集成和持续部署 (CI/CD) 环境测试该包。After creating the Configuration package but before publishing it to Azure, you can test the package from your workstation or continuous integration and continuous deployment (CI/CD) environment. GuestConfiguration cmdlet Test-GuestConfigurationPackage 在开发环境中包含与 Azure 计算机内使用的相同的代理。The GuestConfiguration cmdlet Test-GuestConfigurationPackage includes the same agent in your development environment as is used inside Azure machines. 使用此解决方案,可以在发布到计费的云环境之前,在本地执行集成测试。Using this solution, you can do integration testing locally before releasing to billed cloud environments.

由于代理实际上是在评估本地环境,因此在大多数情况下,你需要在计划审核的同一 OS 平台上运行 Test- cmdlet。Since the agent is actually evaluating the local environment, in most cases you need to run the Test- cmdlet on the same OS platform as you plan to audit. 该测试仅使用内容包中包含的模块。The test only uses modules that are included in the content package.

Test-GuestConfigurationPackage cmdlet 的参数:Parameters of the Test-GuestConfigurationPackage cmdlet:

  • Name:来宾配置策略名称。Name: Guest Configuration policy name.
  • Parameter:以哈希表格式提供的策略参数。Parameter: Policy parameters provided in hashtable format.
  • 路径:来宾配置包的完整路径。Path: Full path of the Guest Configuration package.

运行下面的命令,以测试由上一步创建的包:Run the following command to test the package created by the previous step:

Test-GuestConfigurationPackage `
  -Path ./AuditBitlocker.zip

此 cmdlet 还支持来自 PowerShell 管道的输入。The cmdlet also supports input from the PowerShell pipeline. New-GuestConfigurationPackage cmdlet 的输出通过管道传输到 Test-GuestConfigurationPackage cmdlet。Pipe the output of New-GuestConfigurationPackage cmdlet to the Test-GuestConfigurationPackage cmdlet.

New-GuestConfigurationPackage -Name AuditBitlocker -Configuration ./AuditBitlocker/AuditBitlocker.mof | Test-GuestConfigurationPackage

下一步是将文件发布到 Azure Blob 存储。The next step is to publish the file to Azure Blob Storage. 对存储帐户没有特殊要求,但最好将该文件托管在计算机附近的某个区域中。There are no special requirements for the storage account, but it's a good idea to host the file in a region near your machines. 如果没有存储帐户,请使用以下示例。If you don't have a storage account, use the following example. 下面的命令(包括 Publish-GuestConfigurationPackage)需要 Az.Storage 模块。The commands below, including Publish-GuestConfigurationPackage, require the Az.Storage module.

# Creates a new resource group, storage account, and container
New-AzResourceGroup -name myResourceGroupName -Location ChinaNorth
New-AzStorageAccount -ResourceGroupName myResourceGroupName -Name myStorageAccountName -SkuName 'Standard_LRS' -Location 'chinanorth' | New-AzStorageContainer -Name guestconfiguration -Permission Blob

Publish-GuestConfigurationPackage cmdlet 的参数:Parameters of the Publish-GuestConfigurationPackage cmdlet:

  • Path:要发布的包的位置Path: Location of the package to be published
  • ResourceGroupName:存储帐户所在的资源组的名称ResourceGroupName: Name of the resource group where the storage account is located
  • StorageAccountName:应在其中发布包的存储帐户的名称StorageAccountName: Name of the storage account where the package should be published
  • StorageContainerName:(默认:guestconfiguration)存储帐户中的存储容器的名称StorageContainerName: (default: guestconfiguration) Name of the storage container in the storage account
  • Force:覆盖同名存储帐户中的现有包Force: Overwrite existing package in the storage account with the same name

以下示例将包发布到名为“guestconfiguration”的存储容器。The example below publishes the package to a storage container name 'guestconfiguration'.

Publish-GuestConfigurationPackage -Path ./AuditBitlocker.zip -ResourceGroupName myResourceGroupName -StorageAccountName myStorageAccountName

在创建并上传来宾配置自定义策略包后,创建来宾配置策略定义。Once a Guest Configuration custom policy package has been created and uploaded, create the Guest Configuration policy definition. New-GuestConfigurationPolicy cmdlet 需要使用自定义策略包,并创建策略定义。The New-GuestConfigurationPolicy cmdlet takes a custom policy package and creates a policy definition.

New-GuestConfigurationPolicy cmdlet 的参数:Parameters of the New-GuestConfigurationPolicy cmdlet:

  • ContentUri:来宾配置内容包的公共 http(s) URI。ContentUri: Public http(s) uri of Guest Configuration content package.
  • DisplayName:策略显示名称。DisplayName: Policy display name.
  • 说明:策略说明。Description: Policy description.
  • Parameter:以哈希表格式提供的策略参数。Parameter: Policy parameters provided in hashtable format.
  • 版本:策略版本。Version: Policy version.
  • 路径:在其中创建策略定义的目标路径。Path: Destination path where policy definitions are created.
  • Platform:来宾配置策略和内容包的目标平台 (Windows/Linux)。Platform: Target platform (Windows/Linux) for Guest Configuration policy and content package.
  • Tag 向策略定义添加一个或多个标记筛选器Tag adds one or more tag filters to the policy definition
  • Category 在策略定义中设置类别元数据字段Category sets the category metadata field in the policy definition

下面的示例在自定义策略包的指定路径中创建策略定义:The following example creates the policy definitions in a specified path from a custom policy package:

New-GuestConfigurationPolicy `
    -ContentUri 'https://storageaccountname.blob.core.chinacloudapi.cn/packages/AuditBitLocker.zip?st=2019-07-01T00%3A00%3A00Z&se=2024-07-01T00%3A00%3A00Z&sp=rl&sv=2018-03-28&sr=b&sig=JdUf4nOCo8fvuflOoX%2FnGo4sXqVfP5BYXHzTl3%2BovJo%3D' `
    -DisplayName 'Audit BitLocker Service.' `
    -Description 'Audit if BitLocker is not enabled on Windows machine.' `
    -Path './policies' `
    -Platform 'Windows' `
    -Version 1.0.0 `
    -Verbose

New-GuestConfigurationPolicy 创建以下文件:The following files are created by New-GuestConfigurationPolicy:

  • auditIfNotExists.jsonauditIfNotExists.json

cmdlet 输出中会返回一个对象,其中包含策略文件的计划显示名称和路径。The cmdlet output returns an object containing the initiative display name and path of the policy files.

最后,使用 Publish-GuestConfigurationPolicy cmdlet 发布策略定义。Finally, publish the policy definitions using the Publish-GuestConfigurationPolicy cmdlet. cmdlet 只有 Path 参数,此参数指向 New-GuestConfigurationPolicy 创建的 JSON 文件的位置。The cmdlet only has the Path parameter that points to the location of the JSON files created by New-GuestConfigurationPolicy.

必须有权在 Azure 中创建策略,才能运行发布命令。To run the Publish command, you need access to create policies in Azure. Azure Policy 概述页中收录了具体的授权要求。The specific authorization requirements are documented in the Azure Policy Overview page. 最合适的内置角色是“资源策略参与者”。The best built-in role is Resource Policy Contributor.

Publish-GuestConfigurationPolicy -Path '.\policyDefinitions'

Publish-GuestConfigurationPolicy cmdlet 接受来自 PowerShell 管道的路径。The Publish-GuestConfigurationPolicy cmdlet accepts the path from the PowerShell pipeline. 此功能意味着可以创建策略文件,并在一组管道命令中发布它们。This feature means you can create the policy files and publish them in a single set of piped commands.

New-GuestConfigurationPolicy `
 -ContentUri 'https://storageaccountname.blob.core.chinacloudapi.cn/packages/AuditBitLocker.zip?st=2019-07-01T00%3A00%3A00Z&se=2024-07-01T00%3A00%3A00Z&sp=rl&sv=2018-03-28&sr=b&sig=JdUf4nOCo8fvuflOoX%2FnGo4sXqVfP5BYXHzTl3%2BovJo%3D' `
  -DisplayName 'Audit BitLocker service.' `
  -Description 'Audit if the BitLocker service is not enabled on Windows machine.' `
  -Path './policies' `
 | Publish-GuestConfigurationPolicy

在 Azure 中创建策略后,最后一步是分配定义。With the policy created in Azure, the last step is to assign the definition. 了解如何使用门户Azure CLIAzure PowerShell 分配定义。See how to assign the definition with Portal, Azure CLI, and Azure PowerShell.

使用标记筛选来宾配置策略Filtering Guest Configuration policies using Tags

来宾配置模块中由 cmdlet 创建的策略定义可以视需要选择包括标记筛选器。The policy definitions created by cmdlets in the Guest Configuration module can optionally include a filter for tags. New-GuestConfigurationPolicy 的 Tag 参数支持包含各个标记条目的哈希表数组。The Tag parameter of New-GuestConfigurationPolicy supports an array of hashtables containing individual tag entires. 标记会添加到策略定义的 If 部分,并且不能通过策略分配进行修改。The tags are added to the If section of the policy definition and can't be modified by a policy assignment.

下面给出了筛选标记的策略定义的示例代码片段。An example snippet of a policy definition that filters for tags is given below.

"if": {
  "allOf" : [
    {
      "allOf": [
        {
          "field": "tags.Owner",
          "equals": "BusinessUnit"
        },
        {
          "field": "tags.Role",
          "equals": "Web"
        }
      ]
    },
    {
      // Original Guest Configuration content
    }
  ]
}

使用自定义来宾配置策略定义中的参数Using parameters in custom Guest Configuration policy definitions

来宾配置支持在运行时替代配置属性。Guest Configuration supports overriding properties of a Configuration at run time. 此功能意味着包中 MOF 文件内的值不必被认为是静态的。This feature means that the values in the MOF file in the package don't have to be considered static. 替代值是通过 Azure Policy 提供的,并不会改变配置的创作或编译方式。The override values are provided through Azure Policy and don't change how the Configurations are authored or compiled.

cmdlet New-GuestConfigurationPolicyTest-GuestConfigurationPolicyPackage 包含名为 Parameter 的参数。The cmdlets New-GuestConfigurationPolicy and Test-GuestConfigurationPolicyPackage include a parameter named Parameter. 此参数需要使用包含每个参数的所有详细信息的哈希表定义,并创建用于 Azure Policy 定义的每个文件的必需部分。This parameter takes a hashtable definition including all details about each parameter and creates the required sections of each file used for the Azure Policy definition.

下面的示例创建策略定义来审核服务,其中用户在策略分配时从列表中进行选择。The following example creates a policy definition to audit a service, where the user selects from a list at the time of policy assignment.

# This DSC Resource text:
Service 'UserSelectedNameExample'
      {
          Name = 'ParameterValue'
          Ensure = 'Present'
          State = 'Running'
      }

# Would require the following hashtable:
$PolicyParameterInfo = @(
    @{
        Name = 'ServiceName'                                            # Policy parameter name (mandatory)
        DisplayName = 'windows service name.'                           # Policy parameter display name (mandatory)
        Description = "Name of the windows service to be audited."      # Policy parameter description (optional)
        ResourceType = "Service"                                        # DSC configuration resource type (mandatory)
        ResourceId = 'UserSelectedNameExample'                          # DSC configuration resource id (mandatory)
        ResourcePropertyName = "Name"                                   # DSC configuration resource property name (mandatory)
        DefaultValue = 'winrm'                                          # Policy parameter default value (optional)
        AllowedValues = @('BDESVC','TermService','wuauserv','winrm')    # Policy parameter allowed values (optional)
    }
)

New-GuestConfigurationPolicy
    -ContentUri 'https://storageaccountname.blob.core.chinacloudapi.cn/packages/AuditBitLocker.zip?st=2019-07-01T00%3A00%3A00Z&se=2024-07-01T00%3A00%3A00Z&sp=rl&sv=2018-03-28&sr=b&sig=JdUf4nOCo8fvuflOoX%2FnGo4sXqVfP5BYXHzTl3%2BovJo%3D' `
    -DisplayName 'Audit Windows Service.' `
    -Description 'Audit if a Windows Service is not enabled on Windows machine.' `
    -Path '.\policyDefinitions' `
    -Parameter $PolicyParameterInfo `
    -Version 1.0.0

使用第三方工具扩展来宾配置Extending Guest Configuration with third-party tools

可以扩展来宾配置的项目包以包含第三方工具。The artifact packages for Guest Configuration can be extended to include third-party tools. 扩展来宾配置要求开发两个组件。Extending Guest Configuration requires development of two components.

  • 处理与管理第三方工具相关的所有活动的 Desired State Configuration 资源A Desired State Configuration resource that handles all activity related to managing the third-party tool
    • 安装Install
    • InvokeInvoke
    • 转换输出Convert output
  • 供工具以本机方式使用的格式正确的内容Content in the correct format for the tool to natively consume

如果社区解决方案尚不存在,则 DSC 资源需要自定义开发。The DSC resource requires custom development if a community solution doesn't already exist. 可以通过在 PowerShell 库中搜索标记 GuestConfiguration 来发现社区解决方案。Community solutions can be discovered by searching the PowerShell Gallery for tag GuestConfiguration.

备注

来宾配置扩展性是“自带许可”方案。Guest Configuration extensibility is a "bring your own license" scenario. 使用之前,请确保已满足任何第三方工具的条款和条件。Ensure you have met the terms and conditions of any third party tools before use.

在开发环境中安装 DSC 资源之后,使用 New-GuestConfigurationPackage 的 FilesToInclude 参数在内容项目中包含第三方平台的内容。After the DSC resource has been installed in the development environment, use the FilesToInclude parameter for New-GuestConfigurationPackage to include content for the third-party platform in the content artifact.

策略生命周期Policy lifecycle

如果要发布策略更新,请同时更改来宾配置包和 Azure Policy 定义详细信息。If you would like to release an update to the policy, make the change for both the Guest Configuration package and the Azure Policy definition details.

备注

来宾配置分配的 version 属性仅影响 Microsoft 托管的包。The version property of the Guest Configuration assignment only effects packages that are hosted by Microsoft. 对自定义内容进行版本控制的最佳做法是在文件名中包含版本。The best practice for versioning custom content is to include the version in the file name.

首先,在运行 New-GuestConfigurationPackage 时为包指定一个名称,使其与以前的版本不同。First, when running New-GuestConfigurationPackage, specify a name for the package that makes it unique from previous versions. 可以在名称中包含版本号,例如 PackageName_1.0.0You can include a version number in the name such as PackageName_1.0.0. 使用本示例中的数字只是为了让包独一无二,而不是指定该包应被视为比其他包更新或更旧。The number in this example is only used to make the package unique, not to specify that the package should be considered newer or older than other packages.

接下来,按下面的每项说明更新与 New-GuestConfigurationPolicy cmdlet 一起使用的参数。Second, update the parameters used with the New-GuestConfigurationPolicy cmdlet following each of the explanations below.

  • 版本:运行 New-GuestConfigurationPolicy cmdlet 时,必须指定高于当前发布版本的版本号。Version: When you run the New-GuestConfigurationPolicy cmdlet, you must specify a version number greater than what is currently published.
  • contentUri:运行 New-GuestConfigurationPolicy cmdlet 时,必须为包的位置指定一个 URI。contentUri: When you run the New-GuestConfigurationPolicy cmdlet, you must specify a URI to the location of the package. 在文件名中包含包版本将确保此属性的值在每个版本中都会更改。Including a package version in the file name will ensure the value of this property changes in each release.
  • contentHash:此属性由 New-GuestConfigurationPolicy cmdlet 自动更新。contentHash: This property is updated automatically by the New-GuestConfigurationPolicy cmdlet. 它是 New-GuestConfigurationPackage 创建的包的哈希值。It's a hash value of the package created by New-GuestConfigurationPackage. 对于你发布的 .zip 文件,此属性必须是正确的。The property must be correct for the .zip file you publish. 如果只更新了 contentUri 属性,扩展就不会接受内容包。If only the contentUri property is updated, the Extension won't accept the content package.

发布更新后的包的最简单方法是,重复本文中描述的过程,并提供更新后的版本号。The easiest way to release an updated package is to repeat the process described in this article and provide an updated version number. 该过程可保证正确更新所有属性。That process guarantees all properties have been correctly updated.

可选:为 Guest Configuration 包签名Optional: Signing Guest Configuration packages

来宾配置自定义策略使用 SHA256 哈希来验证策略包是否没有更改。Guest Configuration custom policies use SHA256 hash to validate the policy package hasn't changed. 客户还可以选择使用证书对包进行签名,并强制来宾配置扩展只允许已签名的内容。Optionally, customers may also use a certificate to sign packages and force the Guest Configuration extension to only allow signed content.

若要启用此方案,需要完成两个步骤。To enable this scenario, there are two steps you need to complete. 运行 cmdlet 对内容包进行签名,并将标记追加到应需要对代码进行签名的计算机。Run the cmdlet to sign the content package, and append a tag to the machines that should require code to be signed.

若要使用签名验证功能,请运行 Protect-GuestConfigurationPackage cmdlet,以在发布前对包进行签名。To use the Signature Validation feature, run the Protect-GuestConfigurationPackage cmdlet to sign the package before it's published. 此 cmdlet 需要“代码签名”证书。This cmdlet requires a 'Code Signing' certificate.

$Cert = Get-ChildItem -Path cert:\LocalMachine\My | Where-Object {($_.Subject-eq "CN=mycert") }
Protect-GuestConfigurationPackage -Path .\package\AuditWindowsService\AuditWindowsService.zip -Certificate $Cert -Verbose

Protect-GuestConfigurationPackage cmdlet 的参数:Parameters of the Protect-GuestConfigurationPackage cmdlet:

  • 路径:来宾配置包的完整路径。Path: Full path of the Guest Configuration package.
  • Certificate:用于对包进行签名的代码签名证书。Certificate: Code signing certificate to sign the package. 只有在对 Windows 内容进行签名时,才支持此参数。This parameter is only supported when signing content for Windows.

GuestConfiguration 代理要求证书公钥在 Windows 计算机上的“受信任的根证书颁发机构”和 Linux 计算机上的 /usr/local/share/ca-certificates/extra 路径中存在。GuestConfiguration agent expects the certificate public key to be present in "Trusted Root Certificate Authorities" on Windows machines and in the path /usr/local/share/ca-certificates/extra on Linux machines. 为了让节点能够验证已签名的内容,请先在计算机上安装证书公钥,再应用自定义策略。For the node to verify signed content, install the certificate public key on the machine before applying the custom policy. 可以使用 VM 内的任何技术或使用 Azure Policy 来完成此过程。This process can be done using any technique inside the VM or by using Azure Policy. 此处提供了一个示例模板。An example template is provided here. Key Vault 访问策略必须允许计算资源提供程序在部署过程中访问证书。The Key Vault access policy must allow the Compute resource provider to access certificates during deployments. 有关详细步骤,请参阅在 Azure 资源管理器中为虚拟机设置 Key VaultFor detailed steps, see Set up Key Vault for virtual machines in Azure Resource Manager.

下面是从签名证书导出公钥以导入计算机的示例。Following is an example to export the public key from a signing certificate, to import to the machine.

$Cert = Get-ChildItem -Path cert:\LocalMachine\My | Where-Object {($_.Subject-eq "CN=mycert3") } | Select-Object -First 1
$Cert | Export-Certificate -FilePath "$env:temp\DscPublicKey.cer" -Force

在内容发布后,将名为 GuestConfigPolicyCertificateValidation 且值为 enabled 的标记追加到所有应需要进行代码签名的虚拟机。After your content is published, append a tag with name GuestConfigPolicyCertificateValidation and value enabled to all virtual machines where code signing should be required. 请参阅标记示例,了解如何使用 Azure Policy 大规模传递标记。See the Tag samples for how tags can be delivered at scale using Azure Policy. 在此标记就位后,使用 New-GuestConfigurationPolicy cmdlet 生成的策略定义通过来宾配置扩展启用要求。Once this tag is in place, the policy definition generated using the New-GuestConfigurationPolicy cmdlet enables the requirement through the Guest Configuration extension.

后续步骤Next steps