다음을 통해 공유


MOF 기반 DSC 리소스 작성

이 문서에서는 스키마를 작성하고 IIS 웹 사이트를 관리하는 스크립트 모듈을 개발하여 MOF 기반 DSC 리소스를 만드는 방법을 보여 줍니다.

중요

DSC 3.0부터 MOF 기반 DSC 리소스는 지원되지 않습니다. 새 DSC 리소스를 작성하고 이후 버전에서 작동하도록 하려면 클래스 기반 DSC 리소스 를 대신 작성합니다.

MOF 스키마 만들기

MOF 기반 DSC 리소스에는 소프트웨어 구성 요소에 대한 관리 가능한 설정을 정의하는 스키마(.mof) 파일이 있어야 합니다.

필요한 폴더 구조 만들기

다음 폴더 구조를 만듭니다. 스키마는 파일에 Demo_IISWebsite.schema.mof정의되며 필수 함수는 에 Demo_IISWebsite.psm1정의됩니다. 필요에 따라 모듈 매니페스트(.psd1) 파일을 만들 수 있습니다.

$env:ProgramFiles\WindowsPowerShell\Modules (folder)
    |- MyDscResources (folder)
        |- MyDscResources.psd1 (file, Required)
        |- DSCResources (folder)
            |- Demo_IISWebsite (folder)
                |- Demo_IISWebsite.psd1 (file, optional)
                |- Demo_IISWebsite.psm1 (file, required)
                |- Demo_IISWebsite.schema.mof (file, required)

참고

모듈의 최상위 폴더 아래에 라는 DSCResources 폴더를 만들어야 합니다. 각 DSC 리소스의 폴더는 DSC 리소스와 이름이 같아야 합니다.

MOF 파일의 내용

다음은 DSC 리소스에 대한 웹 사이트의 속성을 설명하는 예제 MOF 파일입니다. 이 예제를 수행하려면 이 스키마를 라는 Demo_IISWebsite.schema.mof파일에 저장합니다.

[ClassVersion("1.0.0"), FriendlyName("Website")]
class Demo_IISWebsite : OMI_BaseResource
{
  [Key] string Name;
  [Required] string PhysicalPath;
  [write,ValueMap{"Present", "Absent"},Values{"Present", "Absent"}] string Ensure;
  [write,ValueMap{"Started","Stopped"},Values{"Started", "Stopped"}] string State;
  [write] string Protocol[];
  [write] string BindingInfo[];
  [write] string ApplicationPool;
  [read] string ID;
};

앞의 코드에 대해 다음 사항에 주목합니다.

  • FriendlyName 은 이 DSC 리소스를 참조하는 데 사용할 수 있는 이름을 정의합니다. 이 예제에서 FriendlyName 은 입니다 Website.
  • DSC 리소스의 클래스는 에서 OMI_BaseResource파생되어야 합니다.
  • 속성의 형식 한정[Key]자인 는 이 속성이 리소스 instance 고유하게 식별한다는 것을 나타냅니다. 모든 DSC 리소스에는 하나 [Key] 이상의 속성이 있어야 합니다.
  • 한정자는 [Required] 이 DSC 리소스를 사용할 때 속성이 필수임을 나타냅니다.
  • 한정자는 [write] 이 속성이 선택 사항임을 나타냅니다.
  • 한정자는 [read] DSC 리소스에서 속성을 설정할 수 없으며 보고 목적으로만 사용됨을 나타냅니다.
  • 은 속성에 할당할 수 있는 값을 ValueMap에 정의된 값 목록으로 제한합니다. 자세한 내용은 ValueMap and Value Qualifiers(ValueMap 및 값 한정자)를 참조합니다.
  • 사용자가 시스템에서 추가하고 제거할 수 있는 DSC 리소스에는 값 PresentAbsent DSC 리소스에 Ensure라는 속성을 포함하는 것이 좋습니다.
  • DSC 리소스에 대한 스키마 파일의 이름을 다음과 같이 지정합니다<classname>.schema.mof. 여기서 <classname> 은 스키마 정의의 class 키워드(keyword) 따르는 식별자입니다.

스크립트 모듈 작성

MOF 기반 DSC 리소스의 스크립트 모듈은 DSC 리소스의 논리를 구현합니다. 이 모듈에서는 Get-TargetResource, Set-TargetResourceTest-TargetResource라는 세 가지 함수를 포함해야 합니다. 세 함수 모두 DSC 리소스 스키마에 정의된 속성 집합과 동일한 매개 변수 집합을 사용해야 합니다. 이 세 함수를 라는 <ResourceName>.psm1파일에 저장합니다. 다음 예제에서는 함수가 라는 Demo_IISWebsite.psm1파일에 저장됩니다.

참고

를 사용하여 Invoke-DscResource 동일한 속성을 두 번 이상 사용하여 원하는 상태를 설정하는 경우 오류가 발생하지 않아야 하며 시스템을 처음 사용한 후와 동일한 상태로 유지되어야 합니다. 이렇게 하려면 및 Get-TargetResourceTest-TargetResource 함수가 시스템을 변경하지 않고 그대로 두고 동일한 매개 변수 값을 가진 시퀀스에서 함수를 Set-TargetResource 두 번 이상 호출하는 것이 항상 한 번 호출하는 것과 동일한지 확인합니다.

함수 구현에서 Get-TargetResource 매개 변수로 제공되는 Key 속성 값을 사용하여 DSC 리소스의 지정된 instance 상태를 확인합니다. 이 함수는 모든 DSC 리소스 속성을 키로 나열하고 이러한 속성의 실제 값을 해당 값으로 나열하는 해시 테이블을 반환해야 합니다. 다음 코드에 예가 나와 있습니다.

# The Get-TargetResource function is used to retrieve the current state of a
# website on the system.
function Get-TargetResource {
    param(
        [ValidateSet("Present", "Absent")]
        [string]$Ensure = "Present",

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Name,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$PhysicalPath,

        [ValidateSet("Started", "Stopped")]
        [string]$State = "Started",

        [string]$ApplicationPool,

        [string[]]$BindingInfo,

        [string[]]$Protocol
    )

        $getTargetResourceResult = $null;

        <#
          Insert logic that uses the mandatory parameter values to get the
          website and assign it to a variable called $Website Set $ensureResult
          to "Present" if the requested website exists and to "Absent" otherwise
        #>

        # Add all Website properties to the hashtable
        # This example assumes that $Website is not null
        $getTargetResourceResult = @{
            Name            = $Website.Name
            Ensure          = $ensureResult
            PhysicalPath    = $Website.physicalPath
            State           = $Website.state
            ID              = $Website.id
            ApplicationPool = $Website.applicationPool
            Protocol        = $Website.bindings.Collection.protocol
            Binding         = $Website.bindings.Collection.bindingInformation
        }

        $getTargetResourceResult
}

사용자가 DSC 리소스의 속성 Set-TargetResource 에 대해 지정하는 값에 따라 다음 중 하나를 수행해야 합니다.

  • 새 웹 사이트 추가
  • 기존 웹 사이트 업데이트
  • 기존 웹 사이트 제거

다음은 이에 대한 예입니다.

# The Set-TargetResource function is used to add, update, or remove a website
# on the system.
function Set-TargetResource {
    [CmdletBinding(SupportsShouldProcess=$true)]
    param(
        [ValidateSet("Present", "Absent")]
        [string]$Ensure = "Present",

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Name,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$PhysicalPath,

        [ValidateSet("Started", "Stopped")]
        [string]$State = "Started",

        [string]$ApplicationPool,

        [string[]]$BindingInfo,

        [string[]]$Protocol
    )

    <#
        If Ensure is set to "Present" and the website specified in the mandatory
          input parameters doesn't exist, then add it using the specified
          parameter values
        Else, if Ensure is set to "Present" and the website does exist, then
          update its properties to match the values provided in the
          non-mandatory parameter values
        Else, if Ensure is set to "Absent" and the website does not exist, then
          do nothing
        Else, if Ensure is set to "Absent" and the website does exist, then
          delete the website
    #>
}

마지막으로, Test-TargetResource 함수는 Get-TargetResourceSet-TargetResource와 동일한 매개 변수 집합을 사용해야 합니다. 구현 Test-TargetResource에서 매개 변수 집합에 지정된 값에 대해 시스템의 현재 상태를 확인합니다. 현재 상태가 원하는 상태와 일치하지 않으면 를 반환합니다 $false. 그렇지 않으면 $true를 반환합니다.

다음 코드는 Test-TargetResource 함수를 구현합니다.

function Test-TargetResource {
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param(
        [ValidateSet("Present","Absent")]
        [System.String]
        $Ensure,

        [parameter(Mandatory = $true)]
        [System.String]
        $Name,

        [parameter(Mandatory = $true)]
        [System.String]
        $PhysicalPath,

        [ValidateSet("Started","Stopped")]
        [System.String]
        $State,

        [System.String[]]
        $Protocol,

        [System.String[]]
        $BindingData,

        [System.String]
        $ApplicationPool
    )

    # Get the current state
    $getParameters = @{
        Ensure          = $Ensure 
        Name            = $Name 
        PhysicalPath    = $PhysicalPath 
        State           = $State 
        ApplicationPool = $ApplicationPool 
        BindingInfo     = $BindingInfo 
        Protocol        = $Protocol
    }
    $currentState = Get-TargetResource @getParameters

    # Write-Verbose "Use this cmdlet to deliver information about command processing."

    # Write-Debug "Use this cmdlet to write debug information while troubleshooting."

    # Include logic to
    $result = [System.Boolean]
    # Add logic to test whether the website is present and its status matches the supplied
    # parameter values. If it does, return true. If it does not, return false.
    $result
}

참고

보다 쉽게 디버깅하려면 이전 세 개의 함수를 구현할 때 Write-Verbose cmdlet을 사용합니다. 이 cmdlet은 자세한 정보 메시지 스트림에 텍스트를 씁니다. 기본적으로 자세한 메시지 스트림은 표시되지 않지만 변수 값을 $VerbosePreference 변경하거나 에 Verbose 매개 변수 Invoke-DscResource를 사용하여 표시할 수 있습니다.

모듈 매니페스트 만들기

마지막으로 cmdlet을 New-ModuleManifest 사용하여 DSC 리소스 모듈에 <ResourceName>.psd1 대한 파일을 정의합니다. 이전 섹션에서 설명한 스크립트 모듈(.psm1) 파일을 NestedModules 매개 변수의 값으로 사용합니다. , Set-TargetResourceTest-TargetResourceFunctionsToExport 매개 변수의 값으로 포함합니다Get-TargetResource.

$ManifestParameters = @{
    Path              = 'Demo_IISWebsite.psd1'
    NestedModules     = 'Demo_IISWebsite.psm1'
    FunctionsToExport = @(
        'Get-TargetResource'
        'Set-TargetResource'
        'Test-TargetResource'
    )
}
New-ModuleManifest @ManifestParameters
@{

# Version number of this module.
ModuleVersion = '1.0'

# ID used to uniquely identify this module
GUID = '6AB5ED33-E923-41d8-A3A4-5ADDA2B301DE'

# Author of this module
Author = 'Contoso'

# Company or vendor of this module
CompanyName = 'Contoso'

# Copyright statement for this module
Copyright = 'Contoso. All rights reserved.'

# Description of the functionality provided by this module
Description = 'Create and configure IIS websites with DSC.'

# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '7.2'

# Modules that must be imported into the global environment prior to importing this module
RequiredModules = @(
    'WebAdministration'
)

# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
NestedModules = @(
    'Demo_IISWebsite.psm1'
)

# Functions to export from this module
FunctionsToExport = @(
    'Get-TargetResource'
    'Set-TargetResource'
    'Test-TargetResource'
)

}

시스템 다시 부팅

함수에서 Set-TargetResource 수행된 작업에 다시 부팅이 필요한 경우 전역 플래그를 사용하여 호출자에게 시스템을 다시 부팅하도록 지시할 수 있습니다.

Set-TargetResource 함수 내에 다음 코드 줄을 추가합니다.

# Include this line if the system requires a reboot.
$global:DSCMachineStatus = 1