Composite Resources
Creating Composite Resources¶
Composite resources in PowerShell Desired State Configuration (DSC) allow you to encapsulate multiple DSC resources into a single reusable module. This approach promotes modularity, reusability, and simplifies complex configurations by abstracting individual components into logical units. Composite resources are particularly useful for scenarios requiring multiple interdependent resources, such as setting up a web server with IIS, a firewall rule, and a service.
Step-by-Step Process¶
-
Define the Composite Resource
Create a script file (e.g.,MyCompositeResource.psm1) containing the composite resource definition. Use theConfigurationkeyword to define the resource and include the required DSC resources. -
Export the Composite Resource
Use theExport-DscResourcecmdlet to generate the.ps1xmlfile that defines the resource in the module. This step ensures the resource is recognized by DSC. -
Package into a Module
Organize the resource files into a module directory structure with a.psd1file to describe the module. This enables the composite resource to be imported and used like any other DSC resource.
Example: Combining File and Registry Resources¶
# MyCompositeResource.psm1
Configuration FileAndRegistrySetup {
param(
[Parameter(Mandatory)]
[string]$FilePath,
[Parameter(Mandatory)]
[string]$RegistryKey
)
Import-DscResource -ModuleName PSDscResources
File CreateFile {
Ensure = 'Present'
Type = 'File'
DestinationPath = $FilePath
Contents = 'This is a test file.'
}
Registry SetRegistryValue {
Ensure = 'Present'
Key = $RegistryKey
ValueName = 'TestValue'
ValueData = 'TestData'
ValueType = 'String'
}
}
Exporting the Resource¶
Run the following command in a separate script or during module creation to export the resource:
Using the Composite Resource¶
After packaging the module, you can use the composite resource in another configuration:
# MyConfiguration.ps1
Import-DscResource -ModuleName MyCompositeModule
Configuration WebServerSetup {
Node localhost {
FileAndRegistrySetup SetupWebServer {
FilePath = 'C:\inetpub\testfile.txt'
RegistryKey = 'HKLM:\Software\TestApp'
}
}
}
WebServerSetup -OutputPath .\ConfigOutput
Key Considerations¶
- Module Structure: The composite resource must reside in a module directory with a valid
.psd1file. - Version Compatibility:
Export-DscResourceis available in PowerShell 5.1 and later. - Testing: Validate the composite resource in isolation before integrating it into larger configurations.
Key takeaways¶
- Composite resources bundle multiple DSC resources into a single reusable module.
- Use
Export-DscResourceto generate the module definition file. - Structure modules with
.psd1and.psm1files for proper recognition. - Composite resources simplify complex configurations by abstracting dependencies.
- Always test composite resources in isolated environments before deployment.