Creating single-instance custom DSC resources

For all that DSC resources are powerful and useful, there are some ways in which you could hurt yourself in their use. One way you could do just that is by using a DSC resource more than once in a DSC configuration. This may sound innocuous at first, but if these two DSC resource declarations had different values for the same parameter, then DSC would continually change the state of the system with each run.

For example, if you defined the xComputer DSC resource twice for the same target node, you would change the name of the target node twice in the DSC run. This sounds silly and would be something you would catch right away. Consider coming back to a couple hundred-lines-long DSC configuration script after several months. Would you remember every DSC resource used in it? Or, consider the same DSC configuration script, except it's maintained by several teams of people who don't necessarily look at the entire script before adding a new DSC resource statement. This is a slightly contrived example, but it proves the point and can show you what can happen in long DSC configuration scripts that are edited by many humans. Contrived examples such as these happen infrequently in real life, where good continuous integration and testing practices are in place.

To implement a single-instance custom DSC resource, add a key property to your DSC resource called IsSingleInstance and limit it to only accept Yes as a value. If you attempt to use a DSC resource twice in the same DSC configuration, compilation will fail, with an error telling you a conflict was detected between resources.

An example Single Instance MOF-based DSC resource is as follows:

powershell
[ClassVersion("1.0.0.0"), FriendlyName("xFooBarBaz")]
class xFooBarBaz : OMI_BaseResource
{
[Key, Description("Specifies the resource is a single instance, the value must be 'Yes'"), ValueMap{"Yes"}, Values{"Yes"}] String IsSingleInstance;
[Required, Description("Specifies the FooBarBaz.")] String FooBarBaz;
};

Each Get, Set, or Test-TargetResource function inside your DSC resource code file would have the following parameter statement:

powershell
function Set-TargetResource
{
[CmdletBinding(SupportsShouldProcess=$true)]
param
(
[parameter(Mandatory = $true)]
[ValidateSet('Yes')]
[String]$IsSingleInstance,
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]$FooBarBaz
)

If you were implementing a single instance class-based DSC resource, you would implement the same parameters as we did in the MOF-based one, except with class properties:

powershell
[DscResource()]
class xFooBarBaz
{
[ValidateSet('Yes')]
[DscProperty(Key)]
[ValidateNotNullorEmpty()]
[String] $IsSingleInstance
[DscProperty(Mandatory)]
[ValidateNotNullorEmpty()]
[String] $FooBarBaz = $null
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset