Create a new Active Directory Forest using Desired State Configuration

Desired State Configuration (DSC) is a declarative language in which you state “what” you want done instead of going into the nitty gritty level to describe exactly how to get it done. Jeffrey Snover (the inventor of PowerShell) quotes Jean-Luc Picard from Star Trek: The Next Generation to describe DSC – it tells the servers to “Make it so”.

In this blog, I will show you how to use DSC to create a brand new Active Directory Forest. In the next blog, for redundancy, we will add another domain controller to this new Active Directory Forest.

The DSC configuration script can be used in conjunction with Azure Resource Manager to deploy an new Active Directory Forest with a single click, how good is that!

A DSC Configuration script uses DSC Resources to describe what needs to be done. DSC Resources are made up of PowerShell script functions, which are used by the Local Configuration Manager to “Make it so”.

Windows PowerShell 4 and Windows PowerShell 5.0, by default come with a limited number of DSC Resources. Don’t let this trouble you, as you can always install more DSC modules to extend this library! It’s as easy as downloading them from a trusted location and placing them in the PowerShell modules directory! 

To get a list of DSC Resources currently installed, within PowerShell, execute the following command

Get-DscResource

Out of the box, there is no DSC modules available to create an Active Directory Forest. So, to start off, lets go download a module that will do this for us.

For our purpose, we will be installing the xActiveDirectory PowerShell module, which can be downloaded from https://gallery.technet.microsoft.com/scriptcenter/xActiveDirectory-f2d573f3  (updates to the xActiveDirectory module is no longer being provided at the above link, instead these are now published on GitHub at https://github.com/PowerShell/xActiveDirectory  . For simplicity, we will use the TechNet link above)

Download the following DSC modules as well

https://gallery.technet.microsoft.com/scriptcenter/xNetworking-Module-818b3583

https://gallery.technet.microsoft.com/scriptcenter/xPendingReboot-PowerShell-b269f154

After downloading the zip files, extract the contents and place them in the PowerShell modules directory located at $env:ProgramFiles\WindowsPowerShell\Modules folder

($env: is a PowerShell reference  to environmental variables).

For most systems, the modules folder is located at C:\ProgramFiles\WindowsPowerShell\Modules

However, if you are unsure, run the following PowerShell command to get the location of $env:ProgramFiles 

Get-ChildItem env:ProgramFiles

Tip: To get a list of all environmental variables, run Get-ChildItem env:

 

With the pre-requisites taken care of, let’s start creating the DSC configuration script.

Open your Windows PowerShell IDE and let’s get started.

Paste the following into your PowerShell editor and save it using a filename of your choice (I have saved mine as CreateNewADForest.ps1)

Configuration CreateNewADForest {
param(
      [Parameter(Mandatory)]
      [String]$DomainName,

      [Parameter(Mandatory)]
      [System.Management.Automation.PSCredential]$AdminCreds,

      [Parameter(Mandatory)]
      [System.Management.Automation.PSCredential]$SafeModeAdminCreds,

      [Parameter(Mandatory)]
      [System.Management.Automation.PSCredential]$myFirstUserCreds,

      [Int]$RetryCount=20,
      [Int]$RetryIntervalSec=30
)

The above declaration defines the parameters that will be passed to our  configuration function.  There are also two “constants” defined as well. I have named my configuration function CreateNewADForest which coincides with the name of the file it is saved in – CreateNewADForest.ps1

Here is some explanation regarding the above parameters and contants

$DomainName         -  FQDN for the Active Directory Domain to create
$AdminCreds         -  a PSCredentials object that contains username and password 
                       that will be assigned to the Domain Administrator account
$SafeModeAdminCreds -  a PSCredentials object that contains the password that will
                       be assigned to the Safe Mode Administrator account
$myFirstUserCreds   -  a PSCredentials object that contains the username and
                       password for the first domain user account to create
$RetryCount         -  defines how many retries should be performed while waiting
                       for the domain to be provisioned
$RetryIntervalSec   -  defines the seconds between each retry to check if the 
                       domain has been provisioned 

 

We now have to import the DSC modules that we had downloaded, so add the following line to the above Configuration Script

Import-DscResource -ModuleName xActiveDirectory, xNetworking, xPendingReboot

We now need to convert $AdminCreds the format domain\username. We will store the result in a new object called $DomainCreds 

[System.Management.Automation.PSCredential]$DomainCreds = New-Object System.Management.Automation.PSCredential ("${DomainName}\$($Admincreds.UserName)", $Admincreds.Password)

 

The next line states where the DSC commands will run. Since we are going to run this script from within the newly provisioned virtual machine, we will use localhost as the location

So enter the following

Node localhost
{

Next, we need to tell the Local Configuration Manager to apply the settings only once, reboot the server if needed (during our setup) and most importantly, to continue on with the configuration after reboot. This is done by using the following lines

 

LocalConfigurationManager
{
     ActionAfterReboot = 'ContinueConfiguration'
     ConfigurationMode = 'ApplyOnly'
     RebootNodeIfNeeded = $true
}

 

If you have worked with Active Directory before, you will be aware of the importance of DNS. Unfortunately, during my testing, I found that a DNS Server is not automatically deployed when creating a new Active Directory Forest. To ensure a DNS Server is present before we start creating a new Active Directory Forest, the following lines are needed in our script

WindowsFeature DNS
{
     Ensure = "Present"
     Name = "DNS"
}

The above is a declarative statement which nicely shows the “Make it so” nature of DSC. The above lines are asking the DSC Resource WindowsFeature to Ensure DNS (which refers to DNS Server) is Present. If it is not Present, then it will be installed, otherwise nothing will be done. This is the purpose of the Ensure = “Present” line. The word DNS after WindowsFeature is just a name I have given to this block of code.

Next, we will leverage on the DSC function xDNSServerAddress (from the xNetworking module we had installed) to set the local computer’s DNS Settings, to its loopback address. This will make the computer refers to the newly installed DNS Server.

xDnsServerAddress DnsServerAddress
{
     Address        = '127.0.0.1'
     InterfaceAlias = 'Ethernet'
     AddressFamily  = 'IPv4'
     DependsOn = "[WindowsFeature]DNS"
}

Notice the DependsOn = “[WindowsFeature]DNS” in the above code. It tells the function that this block of code depends on the [WindowsFeature]DNS section. To put it another way, the above code will only run after the DNS Server has been installed. There you go, we have specified our first dependency.

Next, we will install the Remote Server Administration Tools

WindowsFeature RSAT
{
     Ensure = "Present"
     Name = "RSAT"
}

Now, we will install the Active Directory Domain Services feature in Windows Server. Note, this is just installation of the feature. It does not create the Active Directory Forest.

WindowsFeature ADDSInstall
{
     Ensure = "Present"
     Name = "AD-Domain-Services"
}

 

So far so good. Now for the most important event of all, creating the new Active Directory Forest. For this we will use the xADDomain function from the xActiveDirectory module.

xADDomain FirstDC
{
     DomainName = $DomainName
     DomainAdministratorCredential = $DomainCreds
     SafemodeAdministratorPassword = $SafeModeAdminCreds
     DatabasePath = "C:\NTDS"
     LogPath = "C:\NTDS"
     SysvolPath = "C:\SYSVOL"
     DependsOn = "[WindowsFeature]ADDSInstall","[xDnsServerAddress]DnsServerAddress"
}

 

Notice above, we are pointing the DatabasePath, LogPath and SysvolPath all on to the C: drive. If you need these to be on a separate volume, then ensure an additional data disk is added to your virtual machine and then change the drive letter accordingly in the above code. This section has a dependency on the server’s DNS settings being changed.

If you have previously installed a new Active Directory forest, you will remember how long it takes for the configuration to finish. We have to cater for this in our DSC script, to wait for the Forest to be successfully provisioned, before proceeding. Here, we will leverage on the xWaitForADDomain DSC function (from the xActiveDirectoy module we had installed).

xWaitForADDomain DscForestWait
{
     DomainName = $DomainName
     DomainUserCredential = $DomainCreds
     RetryCount = $RetryCount
     RetryIntervalSec = $RetryIntervalSec
     DependsOn = "[xADDomain]FirstDC"
}

 

Viola! The new Active Directory Forest has been successfully provisioned! Let’s add a new user to Active Directory and then restart the server.

xADUser FirstUser
{
     DomainName = $DomainName
     DomainAdministratorCredential = $DomainCreds
     UserName = $myFirstUserCreds.Username
     Password = $myFirstUserCreds
     Ensure = "Present"
     DependsOn = "[xWaitForADDomain]DscForestWait"
}

The username and password are what had been supplied in the parameters to the configuration function.

That’s it! Our new Active Directory Forest is up and running. All that is needed now is a reboot of the server to complete the configuration!

To reboot the server, we will use the xPendingReboot module (from the xPendingReboot package that we installed)

xPendingReboot Reboot1
{
     Name = "RebootServer"
     DependsOn = "[xWaitForADDomain]DscForestWait"
}

 

Your completed Configuration Script should look like below (I have taken the liberty of closing off all brackets and parenthesis)

Configuration CreateNewADForest {
param
  (
     [Parameter(Mandatory)]
     [String]$DomainName,

     [Parameter(Mandatory)]
     [System.Management.Automation.PSCredential]$AdminCreds,

     [Parameter(Mandatory)]
     [System.Management.Automation.PSCredential]$SafeModeAdminCreds,

     [Parameter(Mandatory)]
     [System.Management.Automation.PSCredential]$myFirstUserCreds,

     [Int]$RetryCount=20,
     [Int]$RetryIntervalSec=30
  )
  Import-DscResource -ModuleName xActiveDirectory, xNetworking, xPendingReboot
  [System.Management.Automation.PSCredential]$DomainCreds = New-Object System.Management.Automation.PSCredential ("${DomainName}\$($Admincreds.UserName)", $Admincreds.Password)

  Node localhost
  {
     LocalConfigurationManager
     {
         ActionAfterReboot = 'ContinueConfiguration'
         ConfigurationMode = 'ApplyOnly'
         RebootNodeIfNeeded = $true
     }

     WindowsFeature DNS
     {
         Ensure = "Present"
         Name = "DNS"
     }

     xDnsServerAddress DnsServerAddress
     {
          Address        = '127.0.0.1'
          InterfaceAlias = 'Ethernet'
          AddressFamily  = 'IPv4'
          DependsOn = "[WindowsFeature]DNS"
     }

     WindowsFeature RSAT
     {
          Ensure = "Present"
          Name = "RSAT"
     }

     WindowsFeature ADDSInstall
     {
          Ensure = "Present"
          Name = "AD-Domain-Services"
     }

     xADDomain FirstDC
     {
          DomainName = $DomainName
          DomainAdministratorCredential = $DomainCreds
          SafemodeAdministratorPassword = $SafeModeAdminCreds
          DatabasePath = "C:\NTDS"
          LogPath = "C:\NTDS"
          SysvolPath = "C:\SYSVOL"
          DependsOn = "[WindowsFeature]ADDSInstall","[xDnsServerAddress]DnsServerAddress"
     }

     xWaitForADDomain DscForestWait
     {
          DomainName = $DomainName
          DomainUserCredential = $DomainCreds
          RetryCount = $RetryCount
          RetryIntervalSec = $RetryIntervalSec
          DependsOn = "[xADDomain]FirstDC"
     }

     xADUser FirstUser
     {
          DomainName = $DomainName
          DomainAdministratorCredential = $DomainCreds
          UserName = $myFirstUserCreds.Username
          Password = $myFirstUserCreds
          Ensure = "Present"
          DependsOn = "[xWaitForADDomain]DscForestWait"
     }

     xPendingReboot Reboot1 
     { 
          Name = "RebootServer" 
          DependsOn = "[xWaitForADDomain]DscForestWait"
     }
  }
}

 

You can copy the above script to a newly create Azure virtual machine and deploy it manually.

However, a more elegant method will be to bootstrap it to your Azure Resource Manager virtual machine template.

One caveat is, the DSC configuration script has to be packaged into a zip file and then uploaded to a location that Azure Resource Manager can access (that means it can’t live on your local computer).

You can upload it to your Azure Storage blob container and use a shared access token to give access to your script or upload it to a public repository like GitHub.

I have packaged and uploaded the script to my GitHub repository at

https://raw.githubusercontent.com/nivleshc/arm/master/CreateNewADForest.zip

The zip file also contains the additional DSC Modules that were downloaded.

To use the above in your Azure Resource Manager template, create a PowerShell DSC Extension and link it to the Azure virtual machine that will become your Active Directory Domain Controller (referred to as DC01 in the code below).

"resources": [
  {
    "type": "Microsoft.Compute/virtualMachines/extensions",
    "name": "[concat(parameters('DC01Name'),'/CreateNewADForest')]",
    "location": "[resourceGroup().location]",
    "apiVersion": "2015-06-15",
    "dependsOn": [
         "[concat('Microsoft.Compute/virtualMachines/', parameters('DC01Name'))]"
    ],
    "tags": {
         "displayName": "CreateNewADForest"
    },
    "properties": {
         "publisher": "Microsoft.Powershell",
         "type": "DSC",
         "typeHandlerVersion": "2.19",
         "autoUpgradeMinorVersion": true,
         "settings": {
              "Modulesurl": "[variables('CreateNewADForestPackageURL')]",
              "ConfigurationFunction":"[variables('CreateNewADForestConfigurationFunction')]",
              "Properties": {
                   "DomainName": "[parameters('domainName')]",
                   "AdminCreds": {
                        "UserName": "[parameters('adminUserName')]",
                        "Password": "PrivateSettingsRef:AdminPassword"
                   },
                   "SafeModeAdminCreds": {
                        "UserName": "[parameters('safemodeAdminUserName')]",
                        "Password": "PrivateSettingsRef:SafeModeAdminPassword"
                   },
                   "myFirstUserCreds": {
                        "UserName": "[parameters('myFirstUserName')]",
                        "Password": "PrivateSettingsRef:MyFirstUserPassword"
                   }

              }
         },
         "protectedSettings": {
               "Items": {
               "AdminPassword": "[parameters('adminPassword')]",
               "SafeModeAdminPassword": "[parameters('safemodeadminPassword')]",
               "MyFirstUserPassword": "[parameters('myFirstUserPassword')]"
         }
    }
  }
]

 

Below is an except of the relevant variables

"repoLocation": "https://raw.githubusercontent.com/nivleshc/arm/master/",
"CreateNewADForestPackageURL": "[concat(variables('repoLocation'), 'CreateNewADForest.zip')]",
"CreateNewADForestConfigurationFunction": "CreateNewADForest.ps1\\CreateNewADForest",

And these are the relevant parameters

That’s it folks! Now you have a new shiny Active Directory Forest, that was created for you using a DSC configuration script.

In the second part of this two-part series, we will add an additional domain controller to this Active Directory Forest using DSC configuration script.

Let me know what you think of the above information.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s