Общие сведения о службе настройки требуемого состояния Windows PowerShell Windows PowerShell Desired State Configuration Overview
Область применения: Windows PowerShell 4.0, Windows PowerShell 5.0 Applies To: Windows PowerShell 4.0, Windows PowerShell 5.0
DSC — это платформа управления в PowerShell, которая позволяет управлять ИТ-инфраструктурой и инфраструктурой разработки с помощью конфигурации в виде кода. DSC is a management platform in PowerShell that enables you to manage your IT and development infrastructure with configuration as code.
- Обзор преимуществ использования DSC для компаний см. в статье Общие сведения о настройке требуемого состояния Windows PowerShell для руководителей. For an overview of the business benefits of using DSC, see Desired State Configuration Overview for Decision Makers.
- Обзор преимуществ использования DSC для инженеров см. в статье Общие сведения о настройке требуемого состояния для инженеров. For an overview of the engineering benefits of using DSC, see Desired State Configuration Overview for Engineers.
- Чтобы начать использовать DSC, см. Краткое руководство по DSC. To start using DSC quickly, see DSC quick start.
Основные понятия Key Concepts
DSC — это декларативная платформа, которая используется для настройки, развертывания и администрирования систем. DSC is a declarative platform used for configuration, deployment, and management of systems. Она состоит из трех основных компонентов: It consists of three primary components:
- Конфигурации — это декларативные сценарии PowerShell, которые определяют и настраивают экземпляры ресурсов. Configurations are declarative PowerShell scripts which define and configure instances of resources. После выполнения конфигурации DSC (а также вызываемые этой конфигурацией ресурсы) принимает ее в исходном виде и обеспечивает существование системы в состоянии, заданном этой конфигурацией. Upon running the configuration, DSC (and the resources being called by the configuration) will simply «make it so», ensuring that the system exists in the state laid out by the configuration. Конфигурации DSC также идемпотентны: локальный диспетчер конфигураций (LCM) следит за тем, чтобы компьютеры находились в состоянии, объявленном конфигурацией. DSC configurations are also idempotent: the Local Configuration Manager (LCM) will continue to ensure that machines are configured in whatever state the configuration declares.
- Ресурсы — это часть DSC. Resources are the «make it so» part of DSC. Они содержат код, который приводит целевой объект конфигурации в указанное состояние и сохраняет это состояние. They contain the code that put and keep the target of a configuration in the specified state. Ресурсы находятся в модулях PowerShell и могут записываться для моделирования обычных объектов, таких как файл или процесс Windows, и специфических элементов, таких как сервер служб IIS или виртуальная машина, работающая в Azure. Resources reside in PowerShell modules and can be written to model something as generic as a file or a Windows process, or as specific as an IIS server or a VM running in Azure.
- Локальный диспетчер конфигураций (LCM) — это механизм, с помощью которого DSC упрощает взаимодействие между ресурсами и конфигурациями. The Local Configuration Manager (LCM) is the engine by which DSC facilitates the interaction between resources and configurations. LCM регулярно опрашивает систему, используя реализуемый ресурсами поток управления, и следит за сохранением состояния, определенного конфигурацией. The LCM regularly polls the system using the control flow implemented by resources to ensure that the state defined by a configuration is maintained. Если система выходит из этого состояния, LCM вызывает код в ресурсах для сохранения заданного конфигурацией состояния. If the system is out of state, the LCM makes calls to the code in resources to «make it so» according to the configuration.
Начало работы с Desired State Configuration (DSC) для Windows Get started with Desired State Configuration (DSC) for Windows
В этом разделе объясняется, как приступить к работе с Desired State Configuration (DSC) в PowerShell для Windows. This topic explains how to get started using PowerShell Desired State Configuration (DSC) for Windows. Общие сведения о службе настройки требуемого состояния см. в разделе Начало работы со службой настройки требуемого состояния Windows PowerShell. For general information about DSC, see Get Started with Windows PowerShell Desired State Configuration.
Поддерживаемые версии операционной системы Windows Supported Windows operation system versions
Поддерживаются следующие версии: The following versions are supported:
- Windows Server 2019 Windows Server 2019
- Windows Server 2016 Windows Server 2016
- Windows Server 2012 R2; Windows Server 2012R2
- Windows Server 2012 Windows Server 2012
- Windows Server 2008 R2 с пакетом обновления 1 (SP1) Windows Server 2008 R2 SP1
- Windows 10 Windows 10
- Windows 8.1 Windows 8.1
- Windows 7 Windows 7
Номер SKU автономного продукта Microsoft Hyper-V Server не содержит реализацию Desired State Configuration, поэтому управлять им с помощью DSC PowerShell или настройки состояния службы автоматизации Azure невозможно. The Microsoft Hyper-V Server standalone product sku doesn’t contain an implementation of Desired State Configuration so it cannot be managed by PowerShell DSC or Azure Automation State Configuration.
Установка DSC Installing DSC
Desired State Configuration в PowerShell входит в состав Windows и обновляется с помощью Windows Management Framework. PowerShell Desired State Configuration is included in Windows and updated through Windows Management Framework. Последняя версия — Windows Management Framework 5.1. The latest version is Windows Management Framework 5.1.
Для управления компьютером с помощью DSC не нужно включать компонент Windows Server «DSC-Service». You do not need to enable the Windows Server feature ‘DSC-Service’ to manage a machine using DSC. Этот компонент необходим только при создании экземпляра опрашиваемого сервера Windows. That feature is only needed when building a Windows Pull Server instance.
Использование DSC для Windows Using DSC for Windows
В следующих разделах описывается создание и запуск конфигураций DSC на компьютерах Windows. The following sections explain how to create and run DSC configurations on Windows computers.
Создание MOF-документа конфигурации Creating a configuration MOF document
Для создания конфигурации используется ключевое слово Windows PowerShell ( Configuration ). The Windows PowerShell Configuration keyword is used to create a configuration. В инструкциях ниже описывается создание документа конфигурации с использованием Windows PowerShell. The following steps describe the creation of a configuration document using Windows PowerShell.
Определите конфигурацию и создайте документ конфигурации: Define a configuration and generate the configuration document:
Установка модуля, содержащего ресурсы DSC Install a module containing DSC resources
Desired State Configuration в Windows PowerShell включает встроенные модули, содержащие ресурсы DSC. Windows PowerShell Desired State Configuration includes built-in modules containing DSC resources. Модули также можно загружать из внешних источников, таких как коллекция PowerShell, с помощью командлетов PowerShellGet. You can also load modules from external sources such as the PowerShell Gallery, using the PowerShellGet cmdlets.
Применение конфигурации к компьютеру Apply the configuration to the machine
Чтобы разрешить выполнение DSC, Windows необходимо настроить для получения удаленных команд PowerShell, даже когда вы запускаете конфигурацию localhost . To allow DSC to run, Windows needs to be configured to receive PowerShell remote commands even when you’re running a localhost configuration. Чтобы правильно настроить среду, запустите Set-WsManQuickConfig -Force в терминале PowerShell с повышенными привилегиями. To easily configure your environment correctly, just run Set-WsManQuickConfig -Force in an elevated PowerShell Terminal.
Документы конфигурации (MOF-файлы) можно применить к компьютеру с помощью командлета Start-DscConfiguration. Configuration documents (MOF files) can be applied to the machineusing the Start-DscConfiguration cmdlet.
Получение данных о текущем состоянии конфигурации Get the current state of the configuration
Командлет Get-DscConfiguration запрашивает текущее состояние компьютера и возвращает текущие значения для конфигурации. The Get-DscConfiguration cmdlet queries the current status of the machine and returns the current values for the configuration.
Командлет Get-DscLocalConfigurationManager возвращает текущую метаконфигурацию, примененную к компьютеру. The Get-DscLocalConfigurationManager cmdlet returns the current meta-configuration applied to the machine.
Удаление текущей конфигурации с компьютера Remove the current configuration from a machine
Настройка параметров в локальном диспетчере конфигураций Configure settings in Local Configuration Manager
Примените MOF-файл метаконфигурации к компьютеру с помощью командлета Set-DSCLocalConfigurationManager. Apply a Meta Configuration MOF file to the machine using the Set-DSCLocalConfigurationManager cmdlet. При этом потребуется указать путь к соответствующему MOF-файлу метаконфигурации. Requires the path to the Meta Configuration MOF.
Файлы журнала Desired State Configuration в Windows PowerShell Windows PowerShell Desired State Configuration log files
Журналы DSC записываются в журнал событий Windows по пути Microsoft-Windows-Dsc/Operational . Logs for DSC are written to Windows Event Log in the path Microsoft-Windows-Dsc/Operational . Дополнительные журналы для отладки можно включить, выполнив действия, описанные в разделе Где находятся журналы событий DSC? Additional logs for debugging purposes can be enabled following the steps in Where Are DSC Event Logs.
Get started with Desired State Configuration (DSC) for Windows
This topic explains how to get started using PowerShell Desired State Configuration (DSC) for Windows. For general information about DSC, see Get Started with Windows PowerShell Desired State Configuration.
Supported Windows operation system versions
The following versions are supported:
- Windows Server 2019
- Windows Server 2016
- Windows Server 2012R2
- Windows Server 2012
- Windows Server 2008 R2 SP1
- Windows 10
- Windows 8.1
- Windows 7
The Microsoft Hyper-V Server standalone product sku doesn’t contain an implementation of Desired State Configuration so it cannot be managed by PowerShell DSC or Azure Automation State Configuration.
Installing DSC
PowerShell Desired State Configuration is included in Windows and updated through Windows Management Framework. The latest version is Windows Management Framework 5.1.
You do not need to enable the Windows Server feature ‘DSC-Service’ to manage a machine using DSC. That feature is only needed when building a Windows Pull Server instance.
Using DSC for Windows
The following sections explain how to create and run DSC configurations on Windows computers.
Creating a configuration MOF document
The Windows PowerShell Configuration keyword is used to create a configuration. The following steps describe the creation of a configuration document using Windows PowerShell.
Define a configuration and generate the configuration document:
Install a module containing DSC resources
Windows PowerShell Desired State Configuration includes built-in modules containing DSC resources. You can also load modules from external sources such as the PowerShell Gallery, using the PowerShellGet cmdlets.
Apply the configuration to the machine
To allow DSC to run, Windows needs to be configured to receive PowerShell remote commands even when you’re running a localhost configuration. To easily configure your environment correctly, just run Set-WsManQuickConfig -Force in an elevated PowerShell Terminal.
Configuration documents (MOF files) can be applied to the machineusing the Start-DscConfiguration cmdlet.
Get the current state of the configuration
The Get-DscConfiguration cmdlet queries the current status of the machine and returns the current values for the configuration.
The Get-DscLocalConfigurationManager cmdlet returns the current meta-configuration applied to the machine.
Remove the current configuration from a machine
Configure settings in Local Configuration Manager
Apply a Meta Configuration MOF file to the machine using the Set-DSCLocalConfigurationManager cmdlet. Requires the path to the Meta Configuration MOF.
Windows PowerShell Desired State Configuration log files
Logs for DSC are written to Windows Event Log in the path Microsoft-Windows-Dsc/Operational . Additional logs for debugging purposes can be enabled following the steps in Where Are DSC Event Logs.