Tag Archives: Desired State Configuration

The current and future state of the Windows Management Framework


At the 2nd of October, Lee Holmes gave a presentation about the current and future state of the Windows Management Framework (WMF) during the Dutch PowerShell User Group (DuPSUG) at the Microsoft headquarters in The Netherlands.

The slide decks and recorded videos will be made available soon, but this is what was discussed:

The release cycle of the Windows Management Framework (WMF)

Faster incremental releases of preview versions are being released. This rapid development means that companies that need specific new functionalities to tackle current problems they’re having, don’t have to wait as long as they had to in the past.

Everyone should keep in mind that documentation for preview versions can be more limited, but should still read the release notes carefully. They contain descriptions of some of the improvements that are discussed in this blog post, but also cover other things that aren’t discussed here. Also be sure to take a look at What’s New in Windows PowerShell at TechNet.

A request from the audience was to include more helpful real-life examples until documentation is fully up-to-date.

 

Desired State Configuration (DSC) partial/split configurations

With DSC partial/split configuration it is possible to combine multiple separate DSC configurations to a single desired state. This could be useful when a company has different people or departments that are responsible for a specific part of the configuration (by example Windows, database, applications).

 

OneGet

OneGet is a Package Manager Manager (it manages package managers). It enables companies to find, get, install and uninstall packages from both internal and public sources. Public repositories can contain harmful files and should be treated accordingly.

Besides the OneGet module included in the Windows Management Framework Preview, updated versions are continuously being uploaded to https://github.com/OneGet/oneget by Microsoft. These can include bug fixes and new functionality like support for more provider types.

While in the past it seemed that Nuget was required, during the PowerShell Summit it was demonstrated that a file share can be used as well.

From the audience a question was raised whether BITS (Background Intelligent Transfer Service) could be used. This is currently not the case and there were also no plans yet to implement it.

 

PowerShellGet

PowerShellGet is a module manager which should make it easier to find the many great modules that are already available, but are not very discoverable because they’re fragmented on numerous websites across the Internet.

Microsoft is currently hosting a gallery of modules. The modules that are available in there are currently being controlled by Microsoft, but this might change in the future.

It is possible to create an internal module source and the save location for modules can be specified as well.

 

PSReadLine

PSReadLine is a bash inspired readline implementation for PowerShell to improve the command line editing experience in the PowerShell.exe console. It includes syntax coloring and CTRL+C and CTRL+V support, for more information about other improvements, view their website.

PSReadLine is one of the modules that can be installed using PowerShellGet:
Find-Module PsReadLine | Install-Module

 

Security

  • Always be careful when running scripts that include Invoke-Expression or its alias iex because it might run harmful code.
    • For a non harmful example, take a look at this blog post by Lee Holmes.
  • Many people in the security community are adopting PowerShell.
  • PowerShell is done in memory and is therefore volatile. To improve security the following enhancements were introduced:
    • Transcript improvements
      • Transcript support was added to the engine so it can used everywhere, also in the Integrated Scripting Environment (ISE).
      • A transcript file name automatically includes the computer name.
      • Transcript logging can be enforced to be redirected to another system.
      • Transcription can be enforced by default.
  • Group Policy
    • An ADMX file is currently not available to configure it on all platforms, but it can be found in the technical preview versions of Windows 10 and Windows Server under: Administrative Templates -> Windows Components -> Windows PowerShell
  • More advanced Scriptblock logging
    • Enable ScriptBlockLogging through GPO (in later Windows versions) or by registry by setting EnableScriptBlockLogging to 1 (REG_DWORD) in: HKLM:\SOFTWARE\Wow6432Node\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging
    • The additional logging will show you what code was run and can be found in event viewer under Applications and Services Logs\Microsoft\Windows\PowerShell\Operational.
    • Scriptblocks can be split across multiple event log entries due to size limitations.
    • Using Get-WinEvent -FilterHashTable it is possible to get related events, extract the information and combine it.
    • Since attackers would want to remove these registry settings and clear event logs, consider using Windows Event Forwarding/SCOM ACS to store this information on another server. Also consider enabling cmdlet logging.
  • Just Enough Admin (JEA)
    • JEA enables organizations to provide operators with only the amount of access required to perform their tasks.

 

New and improved functionality and cmdlets

 

Manage .zip files using Expand-Archive and Compress-Archive

.zip files can be managed using Compress-Archive and Expand-Archive. Other archive types like .rar are not currently supported, but this might be added in future versions.

 

New-Item

It is now not necessary anymore to specify the item type. To create a new item, simply run
New-Item foo.txt

 

Get-ItemPropertyValue

This makes it easier to get the value of a file or registry:

  • Get-ItemPropertyValue $Env:windir\system32\calc.exe -name versioninfo
  • Get-ItemPropertyValue-PathHKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\ScriptedDiagnostics -Name ExecutionPolicy

 

Symbolic links support for New-Item, Remove-Item and Get-ChildItem

Symbolic link files and directories can now be created using:

  • New-Item -ItemType SymbolicLink -Path C:\Temp\MySymLinkFile.txt -Value $pshome\profile.ps1
  • New-Item -ItemType SymbolicLink -Path C:\Temp\MySymLinkDir -Value $pshome

Junctions cannot currently be created, but this might also be added in a later version.

 

Debugging using Enter-PSHostProcess and Exit-PSHostProcess

Let you debug Windows PowerShell scripts in processes separate from the current process that is running in the Windows PowerShell console (by example long running or looping code). Run Enter-PSHostProcess to enter, or attach to, a specific process ID, and then run Get-Runspace to return the active runspaces within the process. Run Exit-PSHostProcess to detach from the process when you are finished debugging the script within the process.

 

Use Psedit to edit files in a remote session directly in ISE

Simply open a new PSSession to a remote computer and type PSEdit <path to a file>.

 

Classes and other user-defined types

    • The goal is to enable a wider range of use cases, simplify development of Windows PowerShell artifacts (such as DSC resources), and accelerate coverage of management surfaces.
    • Classes are useful for structured data. Think by example about custom objects that you need to change afterwards.
    • Name of the class and the constructor must be the same.
    • Code is case insensitive.
    • In classes, variables are lexically scoped (matching braces) instead of dynamically scoped.
    • Every return must be explicit.
    • Sample code:

Class MyClass
{
  MyClass($int1, $int2)
   {
        “In the constructor”
   }
   [int]$Property1
   [DateTime]$Property2
   [int]MyHelper($param1)
   {
       return 42
   } 
}

 

 

 

 

 

 

 

PhillyPoSH 06/05/2014 meeting summary and presentation materials


 

PhillyPoSH June 5th 2014


Meeting Info

Date: June 5th, 2014
Speaker: Jeff Hicks (blog | twitter | google+)
Speaker Topic: Getting Started with Desired State Configuration (DSC)

Registration
Please register if you plan to attend in person or online. The meeting URL to join us remotely will be included in your Eventbrite registration confirmation.

About Jeff
Jeffery Hicks is a multi-year Microsoft MVP in Windows PowerShell, Microsoft Certified Professional and an IT veteran with almost 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He works today as an independent author, trainer and consultant. Jeff writes the popular Prof. PowerShell column for MPCMag.com, is a regular contributor to a variety on online sites, as well as frequent speaker at technology conferences and user groups.

Jeff’s latest books are Learn PowerShell 3 in a Month of LunchesLearn PowerShell Toolmaking in a Month of Lunches and PowerShell in Depth: An Administrators Guide.

You can keep up with Jeff at his blog http://jdhitsolutions.com/blog , on Twitter at twitter.com/jeffhicks and on Google Plus at http:/gplus.to/JeffHicks.

About PhillyPoSH
The Philadelphia PowerShell User Group (PhillyPoSH) is a group of IT Professionals interested in learning and using Windows PowerShell. We encourage PowerShell users of any skill level (from newbie to expert and everything in between) to join.

Meetings are held on the first Thursday of every month at the local Microsoft office in Malvern, PA. We usually have a quick discussion of community news and upcoming events, along with a 30-45 minute technical presentation. Presentations may run longer if we have a guest speaker, but otherwise we usually wrap with a Script Club, where we work together on a particular scripting problem to learn new skills and techniques!

Philadelphia Meeting – June 5th 2014


Join us Thursday, June 5th when Jeff Hicks will present on “Getting Started with Desired State Configuration (DSC)”.

Getting Started with Desired State Configuration (DSC)
DSC is the big game changer for IT Pros. With DSC you no longer have to write PowerShell scripts to manage and configure your servers. Now you use PowerShell to build and manage server configurations. Want your server configured a specific way? Build a configuration and the server configures itself! In this presentation we will look at the principals of DSC and explore what it takes to get started using DSC in your environment.

More about Jeff:
Jeffery Hicks is a multi-year Microsoft MVP in Windows PowerShell, Microsoft Certified Professional and an IT veteran with almost 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He works today as an independent author, trainer and consultant. Jeff writes the popular Prof. PowerShell column for MPCMag.com, is a regular contributor to a variety on online sites, as well as frequent speaker at technology conferences and user groups.

Jeff’s latest books are Learn PowerShell 3 in a Month of Lunches, Learn PowerShell Toolmaking in a Month of Lunches and PowerShell in Depth: An Administrators Guide.

You can keep up with Jeff at his blog http://jdhitsolutions.com/blog , on Twitter at twitter.com/jeffhicks and on Google Plus at http:/gplus.to/JeffHicks.

Please register if you plan to attend in person or online. The meeting URL to join us remotely will be included in your Eventbrite registration confirmation.

Patterns for Implementing a DSC Pull Server Environment


My Patterns for Implementing a DSC Pull Server Environment talk from the PowerShell Summit is now online.

Enjoy!

Building Scalable Configurations With DSC


My Building Scalable Configurations with DSC talk from the PowerShell Summit is now online.

Enjoy!

Going Deeper on DSC Resources


Desired State Configuration is a very new technology and declarative configuration management is a very young space yet.  We (Microsoft and the community) are still figuring out the best structure for resources, composite configurations, and other structures.

That said, there are certain viewpoints that I’ve come to, either from hands on experience or in watching how other communities (like the Puppet community or Chef community) handle similar problems.

How Granular Should I Get?

There is no absolute answer.

Very, Very Granular

Resources should be very granular in the abstract, but in practice, you may need to make concessions to improve the user experience.

For example, when I configure an IP address for a network interface, I can supply a default gateway. A default gateway is a route, which is separate from the interface and IP address, but in practice they tend to be configured together. In this case, it might make sense to offer a resource that can configure both the IP address and the default gateway.

I tend to think resources should be very granular. We can use composite resources to offer higher level views of the configuration. If I were implementing a resource to configure a network adapter’s IP and gateway, I would have a route resource, an IP address resource, and probably a DNS server setting resource. I would then also have a composite resource to deal with the default use case of configuring a network adapter’s IP address, gateway, and DNS servers together.

The benefit of doing it this way is that I still have very discrete, flexible primitives (the IP address resource, the route resource, and the DNS server resource). I can then leverage the route resource to create static routes, or use them directly to more discretely configure the individual elements.

Unless…

You have some flow control that you need to happen based on the state of the client or the environment.  Since your configuration is statically generated and is declarative, there are no flow control statements in the configuration MOF document.  That means that any logic that needs to occur at application time

Unfortunately, this leads to the need to re-implement common functionality.  For example, if I have a service that I need to be able to update the binary (not via an MSI), I need to basically re-implement parts of the file and service resource.  This use case requires a custom resource because I need to stop the service before I can replace the binary, but I don’t want to stop the service with every consistency check if I don’t need to replace the file.

This scenario begs for a better way to leverage existing resources in a cross resource scenario (kind of like RequiredModules in module metadata), but there isn’t a clean way to do this that I’ve found (but I’m still looking!).

My Recommendation

So for most cases, I would try to use existing resources or build very granular custom resources.  If I need to offer a higher level of abstraction, I’d escalate to putting a composite resource on top of those granular resources.  Finally, if I need some flow control or logic for a multistep process, I’d implement a more comprehensive resource.

What Should I Validate?

Now that we are seeing some more resources in the community repository (especially thanks to the waves of resources from the Powershell Team!), we are seeing a variety of levels of validation being performed.

I think that the Test-TargetResource function should validate all the values and states that Set-TargetResource can set.

An example of where this isn’t happening currently is in the cNetworking resource for PSHOrg_cIPAddress.  I’m going to pick on this resource a bit, since it was the catalyst for this discussion.

The resource offers a way to set a default gateway as well as the IP address.  So what happens if after setting the IP and default gateway, someone changes the default gateway to point to another router?

In this case, the validation is only checking that the IP address is correct.  DSC will never re-correct the gateway and our DSC configuration document (the MOF file) is no longer an accurate representation of the system state, despite the fact that the Local Configuration Manager (LCM) will report that everything matches.

This is BAD!!  If a resource offers an option to configure a setting, that setting should be validated by Test-TargetResource, otherwise that setting should be removed from the resource.  The intent of DSC is to control configuration, including changes over time and return a system to the desired state.  If we ignore certain settings, we weaken our trust in the underlying infrastructure of DSC.

What should I return?

The last element I’m going to tackle today is what should be returned from Get-TargetResource.  I’ve been on the fence about this one.  Like with Test-TargetResource, there are a number of implementation examples that vary in how they come up with the return values.

Currently, I don’t see a ton of use for Get-TargetResource and it doesn’t impact the Test and Set phases of the LCM, so it’s been easy to ignore.  This is bad practice (shame on me).

Here’s my thoughts around Get-TargetResource.  It should return the currently configured state of the machine.  Directly returning parameters passed in is misleading.

Going back to the PSHOrg_cIPAddress from the earlier example, it directly returns the default gateway from the parameter, regardless of the configured gateway.  This wouldn’t be so bad if the resource actually checked the gateway during processing and could correct it if it drifted.  But it does not check the gateway, so Get-TargetResource could be lying to you.  T

he most consistent result of Get-TargetResource would be retrieving the currently configured settings.

What’s left?

What other burning questions do you have around DSC?  Let’s keep talking them through either in the forums or in the comments here.

Building Desired State Configuration Custom Resources


Now that we’ve suitably rested, let’s get back to working with Desired State Configuration.  Now, there are some basic features to work with that ship by default and the PowerShell team has been blogging some additional resources, but in order to do some really interesting thing with DSC, we’ll need to create our own resources.

The High Points

The DSC Resource Structure

DSC resources are (at their most basic) a PowerShell module.  These modules are augmented by a schema.mof file (we’ll get into that more in a minute or two).  These modules expose three main functions, Get-TargetResource, Set-TargetResource, and Test-TargetResource.  All three functions should share the same set of parameters.

Test-TargetResource

Test-TargetResource validates whether your resource is currently in the desired state based on the parameters provided.  This function returns a boolean, $true if the resource is in the state described or $false if not.

Set-TargetResource

Set-TargetResource is the workhorse in this module.  This is what will get things into the correct state.  The convention is to support one parameter called Ensure that can take two values, “Present” or “Absent” to describe whether or not a resource should be applied or removed as described.

(Here’s a little trick.. if you write break your Test-TargetResource into discrete functions, you can use those functions to only run the portions of Set-TargetResource that you need to!)

Get-TargetResource

This is currently the least useful of the commands, but if experience has taught me anything, it’ll likely have an a growing use case over time.

Get-TargetResource returns the current state of the of the resource, returning a hash table of properties matching the parameters supplied to the command.

Exporting Commands

This module should explicitly export these commands via either Export-ModuleMember or a module manifest.  If you don’t, Import-DscResource will have trouble loading the resources when you try to generate a configuration (it’s not a problem for running a configuration, just the generation part).

The Managed Object Framework (MOF) Schema

The last piece of the DSC Resource is a schema file that maps the parameters for the command to a CIM class that can be registered in WMI.  This allows us to serialize the configuration parameters to a standards-based format and allows the Local Configuration Manager to marshal the parameters back to call the PowerShell functions for the phase that the LCM is in.  This file is named modulename.schema.mof.

There is no real reason to write a schema.mof file by hand, both the DSC Resource Designer and my New-MofFile function can help generate that function.  The one key thing to be aware of in the schema.mof is that there is an attribute at the top of each of the MOF classes that denotes a friendly name, which is the identifier you will use in a configuration to specify a resource.

[ClassVersion("1.0.0"), FriendlyName("Pagefile")]

How To Structure a Module With Resources

To get a good idea of the resource structure, we can look at the StackExchangeResources module in the PowerShell.Org GitHub repository.  There is a base module – StackExchangeResources, which has a module metadata file (required, you’ll see why in a minute).  In that module, we need a folder DSCResources.  Our custom resource will be placed under that folder.

The reason we need a module metadata file for the base module, is when resources from that module are used in a configuration, the generated configuration MOF files will reference the version of the base module (and that specific version is required on the node where the resource will be applied).

Next up, we’ll talk about how we package our resources to be distributed by a pull server.

IndyPoSh Meeting #10 – Desired State Configuration: Overview and Introduction


Description:

A new breed of configuration management tools has been created to manage the platforms, applications, and infrastructure of the cloud, and keep cloud-related applications and infrastructure running with high availability. The need for these new tools and infrastructure comes from the increase in scale, rapid rate of change, and complexity of the cloud. But existing tools have limited support for Windows. Enter, Windows PowerShell Desired State Configuration (DSC). This rich toolset provides a configuration platform built into Windows that is based on open standards. DSC is flexible enough to function reliably and consistently in each stage of the deployment lifecycle (development, test, pre-production, production), as well as during scale-out, which is required in the cloud world. Among the many great features of DSC is the ability to extend the functionality beyond what is included Out of Box.
This sessions will help with grasping an understanding the why, what and how of DSC. From a simple configuration deployment to more involved deployments and that perhaps would also assist in laying the foundation for cloud-driven infrastructure, public or private.

Speaker:

Enrique Lima (MCITP, MCPD, MCSE+I, MCP+SB, MCT, MCDBA, MCSD, MCAD, CCNA, CCNP, OCP, LCP, LCI, RHCE) has over 18 years of experience in training, application development, database development and management, IT solutions architecture, and project management. Enrique has participated as a speaker and technical learning guide at conferences such as SharePoint Conference 2012, TechEd USA (2004-2013). He was also invited to TechReady 7, 9, 10, 11, 12, 13, 16 and 17, an internal Microsoft conference, as a Subject Matter Expert (SME) in the fields of Windows Azure, Office 365, SQL Server, Platform Virtualization, Application Lifecycle Management/Team Foundation Server, SharePoint Technologies and Service Oriented Architecture.

Enrique has been involved in architecting and developing solutions that leverage the integration of SharePoint Technologies, Windows Azure, Office 365, BizTalk, Commerce Server, and Content Management Server with other Microsoft and non-Microsoft platforms. He has been active in providing guidance in developing and designing solutions that expand and extend those technologies. He actively participated with Microsoft to create material and develop a path to tell the Azure story to IT Professionals and promote Windows Azure beyond just a development platform, also was co-author for Microsoft Official Courseware on SharePoint 2010, Implementation and Configuration (MOC 10174A), was lead author for Microsoft Official Courseware on SQL Server 2005 High Availability Solutions (MOC 2788A), and lead author for Microsoft Official Courseware on Designing Commerce Server 2007 Solutions (50015A). Currently developing and creating new courseware for SharePoint 2013.

Enrique has written, developed, and presented numerous Microsoft and vendor-specific custom classes. As a member of Microsoft’s Global Learning Services, he delivered training and consulting to clients in Latin America, Europe, and Asia.

Enrique’s academic background includes a Bachelor’s of Science, an Electronics Engineering degree, and a Masters of Business Administration from Universidad Francisco Marroquin, Guatemala.  He can be found on twitter on @enriquelima or his blog: http://geekswithblogs.net/enriquelima.

Agenda:

6:00 – 6:30 Food | Networking
6:30 – 6:45 Introduction | Announcements | Speaker Introduction
6:45 – 7:45 Presentation
7:45 – 8:00 Giveaways

Script for Setting Up and Demoing a DSC Pull Server


DSC Setup and Demo Scripts

I recently set up a virtual machine to use for Desired State Configuration (DSC) demos. I wanted to make the demo-ing fairly brainless, as DSC requires a number of setup steps to get a pull server running. So I took some demo scripts Microsoft offered from TechEd 2013, updated them to work with Windows Server 2012 R2 RTM, and thought I’d offer them to you.

SetupDSC.ps1 is the main script. Now, because I didn’t want to use good ol’ Start-Demo, there’s a who crapload of kinda ugly Write-Debug statements. That way I can get an “about to do ____” message and then have the script pause before doing it. Lets me explain to the class what’s about to happen. You can remove all that crud if you like.

InstallPullServerConfig.ps1 and PSWSIISEndpoint.psm1 are the updated Microsoft scripts. SetupDSC.ps1 calls these. They’re intended to run locally; you’ll need to be on the machine you want to make into a pull server, and it needs to be Windows Server 2012 R2 (the DSC pull server role is part of the OS, not part of Windows Management Framework v4). Setup takes a few minutes, and will install IIS. This sets up an HTTP pull server.

SampleConfig.ps1 is a sample DSC configuration, targeted to a computer named MEMBER2. It just specifies that the Windows Server Backup feature be installed. SetupDSC.ps1 actually runs this, which produces a MOF. SetupDSC.ps1 also copies the MOF to the DSC pull server configuration directory.

SampleSetPullMode.ps1 also gets run by SetupDSC.ps1. This contains a DSC Local Configuration Manager configuration, targeted to MEMBER2, that turns on pull mode and directs MEMBER2 to pull the previously-created configuration. I think I have it refreshing every 5 minutes, which is totally unrealistic for production. Again, this was made for class demos, but you can adjust the time or leave it off to default to 30min. Running this script creates the MOF and pushes it to MEMBER2. That, in turn, causes MEMBER2 to start pulling the sample config, which causes Windows Server Backup to be installed.

SetupDSC.ps1 has some additional code to show that Windows Server Backup isn’t installed, and then is installed (after you give the pull time to occur).

Anyway, might need some tweaking to use in production, but hopefully it’ll give you a snapshot of the whole DSC process. Much thanks to James Dawson’s article on DSC, which gave me a couple of the tweaks I needed to get all this working on RTM code.

Enjoy.

IndyPoSh Meeting #9 – What’s New in PowerShell v4


Description:

The November meeting of the Indianapolis PowerShell User Group will present an introduction to PowerShell 4.0. We will discuss new features in PowerShell 4.0 that ship with Server 2012 R2 and Windows 8.1 including Desired State Configuration (DSC), enhancements to the integrated Scripting Environment (ISE) and PowerShell Web Access and more.
In addition we will discuss installing Windows Management Framework 4.0 on Windows 7 SP1, Server 2008 R2 and later systems to bring the new features of PowerShell 4.0 to these operating systems.

Speaker:

John Gullion is a veteran of 18 years in the IT industry. He began his IT career in the mid 90’s working with UNIX, Linux and Windows while supporting dial up internet users and administering smtp mail and nntp news servers. Joining the staff of Indiana University in 2001, John began working with Active Directory and is an accomplished Windows Server and Desktop administrator with expertise in Group Policy Management and PowerShell.

John is a Microsoft Certified Trainer and holds a number of Microsoft and industry certifications including MCSA Server 2012, MCSA Windows 8, MCITP SQL 2008 and  VMWare Certified Professional.

Agenda:

6:00 – 6:30 Food | Networking
6:30 – 6:45 Introduction | Announcements | Speaker Introduction
6:45 – 7:45 Presentation
7:45 – 8:00 Giveaways

Configuring a Desired State Configuration Client


Once we have our pull server in place and we’re starting to create configurations, we need to set up our client nodes to be able to connect to the pull server and how we want the node to behave.

The High Points

Examining the Local Configuration Manager

The Desired State Configuration agent included in Windows Management Framework 4 (or natively on Server 2012 R2 / Windows 8.1) is exposed through the Local Configuration Manager.

PS> Get-DscLocalConfigurationManager

AllowModuleOverwrite           : False
CertificateID                  :
ConfigurationID                :
ConfigurationMode              : ApplyAndMonitor
ConfigurationModeFrequencyMins : 30
Credential                     :
DownloadManagerCustomData      :
DownloadManagerName            :
RebootNodeIfNeeded             : False
RefreshFrequencyMins           : 15
RefreshMode                    : PUSH
PSComputerName                 :

This is where we can configure the behavior of DSC for a particular node.  So, how do we configure it?  With DSC of course!

There is a configuration option LocalConfigurationManager that allows us to set values for the Local Configuration Manager.  A sample configuration looks something like this:

configuration LetsGetConfiguring
{
    param ($NodeId, $PullServer)    

    LocalConfigurationManager
    {
        AllowModuleOverwrite = 'True'
        ConfigurationID = $NodeId
        ConfigurationModeFrequencyMins = 60 
        ConfigurationMode = 'ApplyAndAutoCorrect'
        RebootNodeIfNeeded = 'True'
        RefreshMode = 'PULL' 
        DownloadManagerName = 'WebDownloadManager'
        DownloadManagerCustomData = (@{ServerUrl = "https://$PullServer/psdscpullserver.svc"})
    }
}

While this configuration looks similar to other configurations we might create, we need to apply it with a different command – Set-DscLocalConfigurationManager.

LetsGetConfiguring -NodeId 71defb7f-232b-4213-b289-08c3d424e162 -PullServer pullserver.somedomain.com
Set-DscLocalConfigurationManager -path LetsGetConfiguring

The Local Configuration Manager offers a number of options, which we’ll examine.

AllowModuleOverwrite

This one is pretty straight-forward and only impacts configurations where you are using a pull server.  If you allow module overwrite, newer versions of modules can replace existing modules.  If you don’t enable this, you’ll have to manually remove modules if you want a new copy to pull down.

CertificateID

CertficateID is a thumbprint of a certificate in the machine certificate store that will be used to decrypt any secrets present in the configuration.  DSC allows PSCredential objects to be marshaled through a MOF file, but requires them (without explicit authorization) to be encrypted. (There is another option as well, if you use the ConfigurationData feature, you can also supply the path to a certificate file to use – I’ll be blogging that scenario later when I cover some more advanced scenarios.)

ConfigurationID

The ConfigurationID is a GUID which uniquely identifies what configuration a node should retrieve from a pull server.  If you haven’t had to generate GUIDs before, a really easy way to do so is:

PS> [guid]::NewGuid().Guid

ConfigurationMode

ConfigurationMode defines how the DSC client operates.  There are three valid values:

  • Apply
  • ApplyAndMonitor
  • ApplyAndAutoCorrect

(NOTE:  These descriptions of functionality are based on limited testing – the TechNet documentation is not up to date yet, but should be in the near future.)

Apply will apply the configuration once and after a successful run is logged, it will stop attempting to apply configuration or checking the configuration.  ApplyAndMonitor will apply a configuration as in Apply, but will continue to validate that a node is configured as described.  No corrective action will take place if there is configuration drift.  Finally, ApplyAndAutoCorrect is what most of us think of when looking at DSC as a configuration management tool.  This setting applies a configuration and checks it regularly.  If configuration drift is detected, the configuration manager will attempt to return the machine to the desired state (see how I worked the product name in there..).

ConfigurationModeFrequencyMins

This setting determines how frequently the configured method (the RefreshMode) will be run.  In the case of a pull server, this is how frequently the pull server will be checked for updated configurations.  The minimum value for this is 30.  This value needs to be a multiple of the RefreshFrequencyMins.  If it is not, the engine will treat it as if it was a multiple (rounded up).

Credential

The Credential supplied can be used for accessing remote resources.

DownloadManagerCustomData

DownloadManagerCustomData is a hashtable of values that is passed to the specified download manager.  In the case of a a pull server, the two possible keys are ServerUrl and AllowUnsecureConnection.

DownloadManagerName

Here is where we specify which download manager to use.  DSC ships with two options, the WebDownloadManager (for the web-based pull server) and the DSCFileDownloadManager (for using an SMB share).

RebootNodeIfNeeded

Here’s another pretty self-explanatory setting.  DSC offers a method for resources to request a reboot.  If this setting is $true, then DSC will reboot the node when it is requested.  If it is set to $false, DSC will notify (via the verbose stream and the DSC log) that a reboot is required, but not actually reboot the node.

RefreshFrequencyMins

The RefreshFrequencyMins setting determines how often DSC runs an integrity check against the cached configuration value (or if the check falls on the ConfigurationModeFrequencyMins interval against the pull server if one is configured).  The minimum value for this setting is 15 minutes.

RefreshMode

RefreshMode is either PUSH or PULL.  If you set the RefreshMode to PULL, you’ll need to configure a download manager (via DownloadManagerName).

Next up, we’ll look at how we can build custom resources.

Desired State Configuration – General Availability Changes


PowerShell DSC, along with Windows Server 2012 R2 has reached General Availability!  Yay!

However, there is (at least one so far) breaking change in Desired State Configuration (DSC).

Fortunately, the change is in an area I haven’t blogged about yet.. creating custom resources.  Unfortunately, it does mean I’ll have to update the GitHub repository and all my internal content (should be done by early next week).

The short version is that DSC resources are now resources inside modules, rather than each resource being independent modules.  The benefit of this is that now DSC resources won’t pollute the module scope, each resource won’t need its own psd1 file (the source module will require one though), and it provides an easier way to group resources, which wasn’t really possible before.

So, with GA, resources should go under the module root in a folder DSCResources.  You can have one or more resources in one PowerShell module.  The PowerShell module version is what will be used for the resource version number, so if you have several resources, a version number bump affects all the resources in the module.

I’ll be picking back up with the DSC series next week with how to configure DSC clients, so stay tuned.

Building a Desired State Configuration Configuration – Part 2


Ok, let’s get back to creating a DSC configuration.  If you haven’t read the last post in this series, go back and do that now, I’ll wait.  Now with that out of the way, let’s get back to it…

The High Points

Picking Back UP

Now that we have some of the basics down, we can start to look deeper at how composable these configurations are. A DSC configuration defined in PowerShell offers several advantages, not the least of which is that a configuration can be parameterized.

Parameterization

configuration MyFirstServerConfig
{
	param ([string[]]$NodeName)
	node $NodeName
	{
		WindowsFeature snmp
        {
            Name = 'SNMP-Service'
        }
	}
}

With this simple tweak, I’ve taken a configuration that was hard-coded to one server name to one that can take an array of server names. The PowerShell savvy are probably going, “Big deal.. functions could do that since Monad”. If you remember back in the last post, I showed how ConfigurationData could be used to pass data into a configuration. Then my main configuration did some stuff based on metadata about the node. My configuration was starting to look a bit complicated. The ability to parameterize configurations really helps us when we are ready for the next step, nesting configurations.

Nesting Configurations

Let’s start with an example…

$ConfigurationData = @{
  AllNodes = @(
    @{NodeName = 'Server1';Role='Web'},
    @{NodeName = 'Server2';Role='FileShare'}
    @{NodeName = 'Server3';Role=@('FileShare','Web')}
  )
}

configuration RoleConfiguration
{
	param ($Roles)

	switch ($Roles)
    {
        'FileShare' {
                        WindowsFeature FileSharing
                        {
                            Name = 'FS-FileServer'
                        } 
                    }
        'Web'       {
                        WindowsFeature Web
                        {
                            Name = 'web-Server'
                        } 
                    }        
    }
}

configuration MyFirstServerConfig 
{
    node $allnodes.NodeName
    {
        WindowsFeature snmp
        {
            Name = 'SNMP-Service'
        }       

        RoleConfiguration MyServerRoles
        {
        	Roles = $Node.Role
    	}
    }
}

So, what did we just see? I defined a parameterized configuration and then used it like a DSC Resource in my main configuration. Parameters are passed to the nested configuration in the exact same way as to a DSC Resource. This syntax also means that we can use DependsOn to create dependency chains between groups of functionality more easily.

configuration MyFirstServerConfig 
{
    node $allnodes.NodeName
    {
        WindowsFeature snmp
        {
            Name = 'SNMP-Service'
        }       

        RoleConfiguration MyServerRoles
        {
        	Roles = $Node.Role
        	DependsOn = '[WindowsFeature]snmp'
    	}
    }
}

We can leverage this technique of creating nested configurations to simplify our configuration scripts, minimize dependency chains, and provide an easy way to reuse configuration sections for multiple configurations, all using the same semantics of any DSC resource.

Applying Configurations

Once we have our configurations generated, we have a couple of ways to distribute and apply the configurations. We’ll start assuming that we have generated our configurations for the servers we would like to target.

Start-DscConfiguration

Our first option is Start-DscConfiguration. We can point Start-DscConfiguration to the configuration files that we’ve generated (just point to the directory with the configuration files in them).

Start-DscConfiguration -Path ./MyFirstServerConfig

Doing this will attempt to run the configurations generated against any nodes specified. You can target specific servers by using the -computername or -cimsession parameters.

One downside to using Start-DscConfiguration is that any custom resources (not nested configurations) need to be present on the remote node BEFORE applying the configuration.

You CANNOT create a configuration that uses the file resource (or any other resource) to create the resource on disk during the DSC run. While this would be a cool trick, the resources contain a schema.mof file that defines the interface that DSC can use and the DSC engine will error if it cannot find the resource interface when the configuration is validated before it applies. One option is having two-phased configurations, one to distribute resources and the second to apply it.

Pulling a Configuration

The next alternative is to distribute configurations and resources using a pull Server. In box, DSC supports two types of pull server, an REST based pull server (like described in my previous post) and an SMB based pull server (described here). The pull server requires nodes to be labeled with a GUID (the configuration ID, which we’ll talk about in an upcoming post), instead of server name. The pull server also requires that each config be accompanied by a checksum file with the file hash of the configuration file (example 72ed4117-fc49-4f81-822c-5bc59db64dd3.mof and 72ed4117-fc49-4f81-822c-5bc59db64dd3.mof.checksum).  One word off caution.. there can be no extra whitespace after the hash in the checksum file or the hash check will fail on the client node.  This means you cannot use

Get-FileHash 72ed4117-fc49-4f81-822c-5bc59db64dd3.mof | out-file 72ed4117-fc49-4f81-822c-5bc59db64dd3.mof.checksum

or

Get-FileHash 72ed4117-fc49-4f81-822c-5bc59db64dd3.mof | set-content 72ed4117-fc49-4f81-822c-5bc59db64dd3.mof.checksum

as those leave extra whitespace at the end of the file. I’ve been using

[System.IO.File]::AppendAllText('72ed4117-fc49-4f81-822c-5bc59db64dd3.mof.checksum', (Get-FileHash 72ed4117-fc49-4f81-822c-5bc59db64dd3.mof).Hash)

In my next post, I’ll be talking about we can configure our clients to talk to a pull server, then we can see stuff really start to happen.