Showing posts with label DSC. Show all posts
Showing posts with label DSC. Show all posts

Tuesday, December 02, 2014

Using Pester to validate DSC resources and configurations Part 2

Pester tests are like any other script. They grow and evolve over time. Here are a few more tests that I have testing my DSC resources and configurations that I recently added to my collection. 

Does every resource have a pester test?
This is probably one of the most important tests I have. Every resource should have a test, so why not test for that?

describe "DSCResources located in $PSScriptRoot\DSCResources" {

  foreach($Resource in $ResourceList)
  {
    context $Resource.name {

      it "Has a pester test" {

        ($Resource.fullname + "\*.test.ps1") | should exist
      }

If it is a standard resource, does it have the files it needs?
Each DSC resource needs to have two files in it. A *.psm1 file and a *.schema.mof file. I use the *.psm1 file as a quick way to identify standard resources differently than a composite resource. I know I will not ever reach a test condition that would cause once of these to fail, but I left it in place so I could change the logic later.

if(Test-Path ($Resource.fullname + "\$Resource.psm1"))
{

  it "Has a $Resource.schema.mof" {
                     
    ($Resource.fullname + "\$Resource.schema.mof") | should exist
  }
 
  it "Has a $Resource.psm1" {
                     
    ($Resource.fullname + "\$Resource.psm1") | should exist
  }

Does it pass Test-xDscSchema and Test-xDscResource tests?
I may as well test for these as part of my pester tests. They already validate a lot of things that are easy to overlook.

it "Passes Test-xDscSchema *.schema.mof" {
  Test-xDscSchema ($Resource.fullname + "\$Resource.schema.mof") | should be true
}
 
it "Passes Test-xDscResource" {
  Test-xDscResource $Resource.fullname | should be true
}

If it is a composite resource, does it have the required files?
A composite resource uses different files than a standard resource. It has a *.psd1 and a *.shema.psm1 that should exists. I don’t have any Test-xDSC functions for the composite resources so I add a few extra checks. I verify that the *.psd1 file references the *.psm1 and that the module does not throw any errors when dot sourcing it.

else
{
  it "Has a $Resource.schema.psm1" {
                     
    ($Resource.fullname + "\$Resource.schema.psm1") | should exist
  }
 
  it "Has a $Resource.psd1" {
                     
    ($Resource.fullname + "\$Resource.psd1") | should exist
  }
 
  it "Has a psd1 that loads the schema.psm1" {
 
    ($Resource.fullname + "\$Resource.psd1") | should contain "$Resource.schema.psm1"
  }
 
  it "dot-sourcing should not throw an error" {
 
    $path = ($Resource.fullname + "\$Resource.schema.psm1")
    { Invoke-expression (Get-Content $path -raw) } | should not throw
  }


I hope you find this examples useful. If you want to see more, take a look at part 1.

Tuesday, November 25, 2014

Setting HKey_Curent_User with a DSC resource

I built a fun new resource for managing registry settings. “DSC already has a resource for managing the registry” you say? This one sets values to user registry settings for all users.

    KevMar_UserRegistry DisableScreenSaver
    {
        ID        = "DisableScreenSaver"
        Key       = "HKEY_CURRENT_USER\Control Panel\Desktop"
        ValueName = "ScreenSaveActive"
        ValueData = "0"
    }

How cool is that? The built in DSC registry resource can only manage system settings. For servers this is all you really need. But if you have to manage user settings for some reason, forget about it. You need to use my resource to do it.

There are several limitations with my implementation to understand before we dive into how it works.

First is that this setting applies to all existing users and every new user once it is set. So if you remove this setting from future configurations instead of using the Ensure = "Absent" option, new users to the system will continue to get the setting. The good news is that using Ensure = “Absent” does stop this from applying to new users.

Second is that this sets the value only once per user. This kind of breaks the idea of DSC maintaining configuration drift. If this needs to get reapplied, there is a version attribute that must be used and incremented. Each user keeps track of what version of the setting they have applied. Increasing the version signals the user that something has changed and it needs to be set again. This is important if you are changing the ValueData  to something different.

Third these registry settings are only applied at user logon. I am using a method that hooks into the user logon process to apply the registry settings. I do not flag a reboot to DSC. I considered it but if you are starting to manage user settings, there can be a huge number of these in your configurations. Requiring a reboot for each one feels like a bit much. In my use case, I did not want the reboot. This is why making it as Absent can stop if from applying to any more users.


I’ll do a write up about how I did this in a future post. I used a Windows feature that is not very well known to most systems admins. I have it posted over at https://github.com/kmarquette/Powershell/tree/master/DSCModules/KevMar/DSCResources if you want to check it out.

Thursday, November 20, 2014

$Using: scope in DSC script resources

If you have spent any time working with DSC resources, you have found yourself needing to use the Script resource for some things.

Script Script_Resource
{
    GetScript = {}
    SetScript = {}
    TestScript = {}
    DependsOn = ""
    Credential = ""
}

It is easy enough to use. Define your Get, Set, and Test PowerShell commands and you are all set. Everything is good until you need to work with passing in variables into your script block. You will quickly find that it does not work like you would expect.

This command will always return false:

$path = "c:\windows\temp"
Script Script_Resource
{
    TestScript = {
        Test-Path $path
    }
}

Because $path is not defined within the scope of the TestScript to a value, the Test-Path will return false. Take a look at the mof file and you can see this. 

instance of MSFT_ScriptResource as $MSFT_ScriptResource1ref
{
 ResourceID = "[Script]Script_Resource";
 TestScript = "\n Test-Path '$path'\n ";
 SourceInfo = "::7::9::Script";
 ModuleName = "PSDesiredStateConfiguration";
 ModuleVersion = "1.0";

};


I have found two ways to deal with this issue. If you think about it, the TestScript is just a string that gets ran on the target node. If you look at the resource, TestScript is defined as a String.

$path = "c:\windows\temp"
Script Script_Resource
{
    TestScript ="Test-Path '$path'"
}


This works really well when the command is a very simple one line script. Take a look at the mof file now.

instance of MSFT_ScriptResource as $MSFT_ScriptResource1ref
{
 ResourceID = "[Script]Script_Resource";
 TestScript = "Test-Path 'c:\\windows\\temp'";
 SourceInfo = "::6::9::Script";
 ModuleName = "PSDesiredStateConfiguration";
 ModuleVersion = "1.0";

}; 

This could end up very messy if the script block gets more complicated. What if you have variables that you want to define in the script and use some from the parent scope. You end up escaping things with that horrible back tick. But there is a better way.

This is where the $using: scope comes to the rescue. As far as I can tell, this is undocumented for use in script resources. But using it in Invoke-Command script blocks will allow you to reference variables in the parent scope. It works for our script resource too.

$path = "c:\windows\temp"
Script Script_Resource
{
    TestScript = {
        Test-Path $using:path
    }
} 

Now when we dive into the mof file, we can see just how this magic works. Our $path gets inserted into the script as part of the script. 

instance of MSFT_ScriptResource as $MSFT_ScriptResource1ref
{
 ResourceID = "[Script]Script_Resource";
 TestScript = "$path='c:\\windows\\temp'\n Test-Path $path\n ";
 SourceInfo = "::7::9::Script";
 ModuleName = "PSDesiredStateConfiguration";
 ModuleVersion = "1.0";
};

The $using: scope is something I often overlook but this will be a very handy way to use it.

One final note about my examples. I did trim them down to minimize the code. If you want to recreate my tests, you will need to have the SetScript and GetScript properties defined for each script block.

Wednesday, June 25, 2014

LocalConfigurationManager{ DebugMode = $true }

One issue that I ran into when writing my custom DSC resources is that the local resource manager would cache the modules I was working on. It took me a while to realize that was going on. That is when I discovered DebugMode for the local resource manager.

If you enable debug mode, then it will reload the module every time. This is off by default for performance reasons. You have to use a DSC configuration to configure this, but it is done in a slightly different way than normal DSC configurations. Technet has all the details on how to configure the local resource manager. That is where I pulled this sample code from.

If all you want to do is enable debug mode, here is the quick script to do that:

Configuration ExampleConfig
{
    Node "localhost"
    {
        LocalConfigurationManager
        {
            DebugMode = $true
        }
    }
}

# The following line invokes the configuration and creates a file called localhost.meta.mof at the specified path
ExampleConfig -OutputPath "c:\users\public\dsc"

# Notice the use of Set-DSCLocalConfigurationManager
Set-DscLocalConfigurationManager -Path "c:\users\public\dsc"

If you are not using WMF5 CTP Release, then you have to fall back on killing the process hosting DSC. Here is a quick script to do that:

# find the Process that is hosting the DSC engine
$dscProcessID = Get-WmiObject msft_providers | 
  Where-Object {$_.provider -like 'dsccore'} | 
  Select-Object -ExpandProperty HostProcessIdentifier 

# Kill it
Get-Process -Id $dscProcessID | Stop-Process

Wednesday, June 18, 2014

KevMar_TcpPrinter v1.0.2

I just pushed an update to my TcpPrinter resource that can now handle basic driver installations. You can optionally provide a path to the inf files needed for the installation. The resource will try and use those if the driver does not exist.

There will be some limitations to this approach but I felt it was important to provide this option. For now, make sure the files are on the target system. You may have to use another resource to copy those files to the target.

Another change in this release is that Ensure="Absent" will try and remove the port and driver if they are not in use anymore. Should help to keep the system a little cleaner. I did add the requirement that the DriverInf property should be defined for it to remove a driver. This assumes that you installed the driver with this resource and can easily add it again. I also wanted to avoid removing any of the built in drivers.

Changes in v1.0.2
  Added DriverInf property
    Allows you to provide the location to the driver's inf file to be used during printer installation
  Modified Ensure="Absent"
    Will remove the printer port if the removed printer was the last one using it
    Will remove the driver only if the DriverInf is defined and the removed printer was the last one using it

https://github.com/kmarquette/Powershell

Monday, June 16, 2014

DSC Resource: KevMar_MapPrinter

Last week I put together a resource for adding TCP printers with Desired State Configuration. After I finished that one, I knew I needed to create another one that loads printers from a print server. They hand in hand even if they have different use cases. I can see using TcpPrinter for a print server and MapPrinter for a terminal server.

This one turned out to be much simpler to put together. I may end up doing a more detailed write up in the future just to show how easy it can be to create a DSC resource. Take a look at how simple the config looks for MapPrinter.

 
MapPrinter NetworkPrinter
       {
            Path = '\\server\EpsonPrinter'            
       }

It does not get much simpler than that. And removing a printer mapped this way is just as easy.

MapPrinter NetworkPrinter
       {
            Path   =  '\\server\EpsonPrinter'            
            Ensure = "Absent"
       }

This will map this printer for every user on the system. There is no way to target just a user with the method that I used. To correctly remove a printer mapped this way, it is best to use the DSC resource to do so. If you have to remove it by hand, here is the command that does the magic.

$path = "\\server\EpsonPrinter"
rundll32 printui.dll,PrintUIEntry /gd /n$path

It feels like the printer is slow to show up the first time this is ran. Restarting the spooler speeds up the process. I don't think the spooler immediately sees the changes.

The KevMar_MapPrinter was added to my other module that I have up on https://github.com/kmarquette/Powershell

Friday, June 13, 2014

DSC Resources: KevMar_TcpPrinter, KevMar_WindowsUpdate

I put together a set of Desired State Configuration Resources into a module. I was looking for a good project and I did not see any other resources that managed printers or Windows Updates yet.

KevMar_TcpPrinter

This is a printer management resource that will also create printer ports as needed. Most of the settings are optional as long as you specify the name, driver, and ip address of the printer.

At the moment, the driver already needs to be installed on the target node. Driver management is one of the next things for me to look at after I do some more testing.

KevMar_WindowsUpdates

The Windows Updates module is a composite module that wraps together several registry resources. Each of those properties maps to one or more registry keys that relates to automatic updates

I have all the code up on https://github.com/kmarquette/Powershell with some example configurations.


Why can't things just work?

I love to learn new things. I tend to dive in and just run with it. I just put together a new DSC resource for managing printers. Everything felt very solid as I was testing and things were just working. Running the Get,Set,and Test TargetResource commands by hand felt solid. Then I created my first config and pushed it with a Start-DscConfiguration. I ran into one small little issue that turned into a major road block.

How hard can it be to add a printer?

Under the hood, I was just using WMI to add printers and printer ports. I could easily update and delete existing printers. I could also create new printer ports without issue. My major road block was that my code to create a new printer would only fail when ran with Start-DscConfiguration. One little feature that is kind of critical to the whole project.

Win32_Printer.Put()

I was creating a new Win32_Printer object and using the .Put() command to save it. The error message I got was very nondescript. I used a try/catch block to report back the inner message of the exception. Access Denied is all it said.

I tried creating WMI objects different ways but I was not making any progress. I validated all the properties and tested setting more/less of them at once. I took a closer look at the .Put() command and found it had a putOptions overload. I had to track down how to create the right object because it didn't accept the raw int values. I discovered that there was a .psbase.put() command that I was not using before. Trial and error.

VBScript 

I also discovered that Powershell and VBScript use different wrappers for WMI objects. For some reason VBScript uses a .put_() command (yes, that underscore is intentional) to commit changes. I was able to use an existing VBScript in the Windows folder so I didn't have to write my own. It worked well enough with manual testing, but it also failed to work correctly when ran as a DscResource. I had hope that the different wrappers would somehow make a difference. But I was mistaken.

CIM_Printer

I would have loved to have used New-Printer but I am working with Windows 7. But that gave me an idea to look at the CIM instances. Again, a different wrapper. While the CIM_Printer class is easy to pull data out with, I don't think it was ever intended to be used for adding printers. I tried to create a new object but did not have much luck. As I explored the object, all the properties look to be read only. When trying to create a new one, it complains about the key fields missing. Yet when I tried to work that out, I didn't make any progress.

rundll32.exe

I figured there had to be some way to add a printer from the command line without using WMI. I tracked down a rundll32 command that I used in the past for other things (Rundll32 printui.dll,PrintUIEntry). I had a good feeling that it would have worked. I didn't like the required parameters as much. Mostly because it wanted more details around the driver than I was using. Something I could change, but it didn't feel as clean as I wanted this part to be. But it did give me another idea.

pInvoke

I started to look at system calls and found the AddPrinter that I was looking for. I required exactly what I wanted it to require. It was almost too good to be true. I was then looking at my next challenge. How do I pInvoke from Powershell? I found a little snip of code where they used C# to do the pInvoke from Powershell. That looked like as good of an approach as any.

C# and Powershell

I had my C# code fleshed out and needed to get it running in Powershell. I want to avoid having an external assembly so I had to figure out how to do it more inline. The Add-Type command turned out to be exactly what I was looking for. After importing my C# code, I was off an running.

It just works

I was able to drop it into my DSC resource with minimal adjustment and it worked perfectly. That last piece fell into place and my DSC resource was working wonderfully. This project started out as one of the most basic resources that I could think of and it ended up taking me on journey across many different technologies before I was done.

The end result is a TCPPrinter DSC resource that I have added to my KevMar modules.

Monday, June 02, 2014

Writing DSC Resources in C#

I wanted to mention this real quick so that I could find it later. The Powershell blog just mentioned that you can write DSC resources in C#.

http://blogs.msdn.com/b/powershell/archive/2014/05/29/wish-i-can-author-dsc-resource-in-c.aspx

Sunday, June 01, 2014

Using Desired State Configuration to Set Local Passwords

DSC as a User resource that allows you to create and configure local accounts. While you can set the local account password this way, you have to store the password in plain text to do so. So if you decide to set the administrator password this way, the mof file on the machine will contain that password in plain text. This is a perfect example of just because you can do something, it does not mean that you should.

This turned out to be more complicated than I expected. I was able to find a post by Aman Dhally that dug into the details and this was the result.


$ConfigData = @{
    AllNodes = @( 
             @{ NodeName = "*"; PSDscAllowPlainTextPassword=$true }
             @{ NodeName = "localhost"; }
    );
}


Configuration LocalPasswordConfig
{
    $secpassword = ConvertTo-SecureString "Password1" -AsPlainText -Force
    $mycreds = New-Object System.Management.Automation.PSCredential("Administrator",$secpassword)

    Node $AllNodes.NodeName
    {
        User LocalAccount{
            UserName = "Administrator"
            Password = $mycreds
        }
    }
}

If you don't want to have your password in plain text in your config files, you can pass in a credential object. But the .mof file will still have the plain text password.


Configuration LocalPasswordConfig
{
    param([PsCredential]$mycreds)

    Node $AllNodes.NodeName
    {
        User LocalAccount{
            UserName = "Administrator"
            Password = $mycreds
        }
    }
}

$cred = Get-Credential
LocalPasswordConfig -mycreds $cred –ConfigurationData $ConfigData 

It may be possible to use a certificate to solve the pain text issue, but I am still trying to get my head wrapped around it. I see what looks like a good example here. See the example script at the bottom of that page.

Monday, May 19, 2014

Why Powershell Desired State Configuration?

I am a huge fan of Powershell. I use it where I can to manage my infrastructure and workstations. Powershell remoting is such a wonderful thing. I start to think about my infrastructure as nodes or objects in code. As someone that shifted into IT from development, this becomes a very powerful tool. 

I craft and test my commands on test workstations. I then take those commands and order all of my nodes in AD to go take care of it. I see a job spin off for every one at almost the same time. And I know they are doing exactly what I am telling them to do. It just gives you that feeling of power. It is even better when you can see and hear it happening.

Our largest dental clinic has 50 chars in it. Each cubicle has dividers between them, 2 people could stand up in opposite corners of this large room and they could see each other. There is a central control station that faculty use where I love to issue remote commands. When I send something like Wake On Lan to all the clinics, I can hear every machine in there click on at almost the same time. I can hear the fans spin up and I can see the monitor glow cast a blue shine across the room. There is nothing like seeing your code interact with the real world like that.

This is the perfect fix it now type of remote scripting. This is great for when I want to refresh group policy for flush DNS on every node. I target my Active Directory nodes and say go take care of this. But not every script is a fix it now type of script.

Because I blindly target nodes when I do this, some slip through the cracks. Maybe WOL was miss configured, bios has a low battery warning, the mobile user is out of the office, or it is a spare machine sitting on a shelf. I am left with several machines for whatever reason missed the script. I don't care so much when I flush dns on everything but what about enabling bitlocker? That just has to get taken care of. So I have to decide how to handle this going forward. GPO, SCCM, scheduled task on some random box, or I run this script again when I think about it. 

Personally, I make that call case by case and use whatever I think is best for the change. I have to consider newly deployed machines, returning machines, and how likely those settings will drift. And this is where Desired State Config starts to enter the picture. We have to remember it is just another tool like GPO or SCCM, but it does have a lot to offer.
DSC lets you declare how a system should look, and it will take care of it for you. You once again get to say "make it so" and the system takes action. Not only does this set configurations on nodes, it makes sure they stay configured. With a pull server in place, they never miss a command. You set it and forget it. 

I am just getting started with DSC and I love the idea. Still not sure it is the best match for my current environment, but I think it is important we take notice of it. I felt Powershell was overlooked by a lot of people for the longest time. Step back and see how important Powershell has become already. And when they Jeffery Snover says the reason they created Powershell was so that they could create Desired State Config, you know this is something you should pay attention to.

I don't think we will see this for workstation management yet, it is only a matter of time before we see tools like SCCM switch over to use DSC.