PowerShell DSC Primer
Posted on January 30, 2018
- and tagged as
- powershell,
- dsc
PowerShell Desired State Configuration (DSC) works in either Push or Pull mode. In Push mode the DSC configuration is ‘pushed’ to the server (usually by copying the files), and executed there. In Pull mode, the server queries a Pull server and grabs it’s own configuration. Pull mode allows the server to periodically check in to confirm it’s configuration is still correct.
Push Mode
To begin with, let’s start with the quickest, a simple Push script. This will ensure the IIS Feature is installed, and create an index.html in the document root to be served.
Configuration IISTest {
Import-DscResource -ModuleName PSDesiredStateConfiguration
Node 'localhost' {
WindowsFeature WebServer {
Ensure = "Present"
Name = "Web-Server"
}
File WebsiteContent {
Ensure = "Present"
Contents = "<head></head>
<body>
<p>Hello World!</p>
</body>
"
DestinationPath = "C:\inetpub\wwwroot\index.html"
}
}
}
Once we have our configuration, it needs to be turned into a .mof file. This is done by dot sourcing the above file, and running the IISTest function. It is also possible to include the IISTest at the bottom of the configuration file, and simply run the file.
PS C:\> . .\WebsiteTest.ps1
PS C:\> IISTest
This process will create a new folder with the name of the function (IISTest), and inside will be a single .mof file with the name of the Node (localhost).
This folder can then be copied to the server which needs to be configured, and we can run DSC to configure the system.
PS C:\> Start-DscConfiguration .\IISTest
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
2 Job2 Configuratio... Running True localhost Start-DscConfiguration...
Get-DscConfiguration
and Get-Job
can be used to confirm whether the DSC task has completed. Test-DscConfiguration
can be used to confirm that configuration was completed successfully, i.e, what the actual configuration on the nodes matches the desired configuration.
PS C:\> Test-DscConfiguration
True
This can be used at a later date to verify whether the configuration is still correctly applied. For example, if we rename the index.html file, we get the following.
PS C:\> Test-DscConfiguration
False
Once done, we should be able to load http://localhost in a browser and see our site.