Wednesday, June 14, 2017

PowerShell + .psd1 files - decouple environment configuration data from code


What is environment configuration data?


Well, you might have heard the term 'configuration data' in usage with PowerShell DSC. The case for using configuration data is wherein all the input arguments are abstracted from the code being written so that this configuration data can be generated on the fly and passed to the underlying scripts or framework like DSC.


For some of our solutions being deployed at the customer site, we require a lot of input parameters e.g. different network subnets for management and storage networks, AD/DNS information etc.


Adding all these parameters to our input argument collector script was an error prone and tedious task since there were far too many input arguments. So instead of having a file to specify all input arguments was the preferred method.

This also helped us while troubleshooting the deployments since a local copy of the input arguments always persisted.





.PSD1 vs .JSON ?


We started with using JSON files first but later realized below salient points of using .psd1 files:


  1. .PSD1 files are native and first class citizens on PowerShell. 
  2. Also the ability to put comments in the .psd1 files. 
  3. PowerShell ISE (native to Windows Server OS) is able to edit the .psd1 files with ease.

Below I would like to take a moment and highlight a bit more on the above points.

1) .PSD1 file support in PowerShell

There was an ugly way of using the Import-LocalizedData cmdlet to read the .psd1 files. But since WMF 5.0 a function named Import-PowerShellDataFile was added. Read this PowerShell Magazine article by Ravi here.

2) .PSD1 file supports placing inline comments

In the .psd1 file you can place inline comments to mention what that input field represents. Along with this information, we also use comments to mention if a field needs to be modified or not in our .psd1 files.

3) PowerShell ISE support to edit .PSD1 files

Since our engineered solutions are mostly run from a Windows box, there is PowerShell ISE present out of the box present which allows deployment engineers to edit the files and highlight any syntax errors.




All being said, we do support consuming .JSON files in our engineered solutions for input too, since both .psd1 and .json file formats are for data storage and consuming them is a straightforward in PowerShell e.g. our PSRemotely module supports passing configuration data in both .psd1 and .json file formats.

2 comments: