Friday, October 9, 2020

Join a VM to an active directory domain in Azure with PowerShell

 At current client we have a hybrid setup with an on-prem datacenter and VPN connections to Azure. The on-prem active directory has been extended to Azure with an additional two domain controllers (classic active directory).

We have a generic virtual machine deployment template in PowerShell and want to be able to have VMs automatically join the domain as part of the deployment process.

A first learning is to make sure that the IP addresses of the DC's are specified as custom DNS servers on the VNets where they reside (assuming they also function as DNS servers). Otherwise, the VMs won't be able to resolve the domain (VNet -> DNS servers -> Custom).

Up front we have verified that a VM can be manually joined to the domain from the VM itself.

The PowerShell command for setting the domain is: Set-AzVMADDomainExtension

The MS documentation is not very thoroughly described for this command, unfortunately.

We got pretty far using this guide instead.

When using that example and trying jo join, the PowerShell script kept hanging and timing out. From the VM itself in the event log, it just stated NetJoin action failed. But no helpful error description.

We had to adjust two things to make it work:

1. For the JoinOption parameter, instead of using 0x00000001, we used 0x00000003 (which is similar to setting 0x00000001 and 0x00000002). This specifies joining a domain instead only a workgroup (option 1) and option 2 creates an account on the domain.

2. By using the Invoke-AzVMRunCommand command we set the DNS suffix from inside the VM using PowerShell before running the domain join command.

This works in our setup. The code examples can be seen below (first script calls the second script). It can be added to an existing VM deployment script or be run as a standalone script post VM install.

Join domain

# Update variables
$VMName = "XXVMname"
$ResourceGroupName = "XX-RGname"

# Do not update these variables
$DomainName = "XXdomainname.local"
$ServiceAcct = "XXdomainname\XXserviceaccountname"
$secretnameDomain = "XXnameofsecretinKeyVault"
$JoinOpt = "0x00000003" # specifies the options to join a domain, 0x00000001 + 0x00000002
$OU = "OU=XX,OU=XX,DC=XX,DC=Local" # Update string with corrrect OU path (not a requirement)
$kvname = "XXnameofKeyVault"
$LocationName = "westeurope"
$ScriptPathDNSsuffix = ".\SetDnsSuffixInVM.ps1"

Write-Host "Set DNS suffix in VM. $(Get-Date)"
# Set DNS suffix in VM (for domain join to work)
Invoke-AzVMRunCommand -ResourceGroupName $ResourceGroupName `
 -VMName $VMName `
 -CommandId 'RunPowerShellScript' `
 -ScriptPath $ScriptPathDNSsuffix

# Get service account password from key vault
$ServiceAcctPassword = (Get-AzKeyVaultSecret -vaultName $kvname -name $secretnameDomain).SecretValueText | ConvertTo-SecureString -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ($ServiceAcct, $ServiceAcctPassword);

Write-Host "Joining domain $DomainName. $(Get-Date)"
Set-AzVMADDomainExtension -DomainName $DomainName `
 -VMName $VMName `
 -ResourceGroupName $ResourceGroupName `
 -Location $LocationName `
 -Credential $Credential `
 -OUPath $OU `
 -JoinOption $JoinOpt `
 -Restart `
Write-Host "Script done at $(Get-Date)"

Set DNS Suffix in VM (SetDnsSuffixInVM.ps1)

$DnsSuffix = "XXDomainname.local"

$interfacealias = get-dnsclient | Where-Object {$_.InterfaceAlias -eq "Ethernet"}
set-dnsclient -Interfaceindex $interfacealias.Interfaceindex `
-ConnectionSpecificSuffix $DnsSuffix `
-RegisterThisConnectionsAddress $True

Thursday, October 1, 2020

Azure: Allowing Windows Server to activate via KMS through Azure Firewall

 At current client we have an Azure Firewall installed. And only outbound traffic on ports 80 and 443 is allowed. Today we found that Windows Servers do not activate (we're buying the licenses per Windows Server). 

The reason for this is that the VMs can't reach the KMS server for Azure Global cloud:

Azure Global KMS:  - IP: on port 1688. See here for more info. 

(I found a general activation troubleshooting guide here where they recommend testing with PsPing. I didn't get around to trying that, but it might be useful.)

I tried adding a network rule in the Azure Firewall using the FQDN, That failed.

But adding a rule using the IP address in stead worked fine (and that looks to be 'allowed' as well by MS).

The following rule was added in Azure Firewall via PowerShell:

 # Allow VMs to reach for Windows Server activation
 $NetRule2 = New-AzFirewallNetworkRule -Name "allow-kms" -Protocol TCP,UDP -SourceAddress `
  "", `
  "" `
 -DestinationAddress "" -DestinationPort "1688"

And remember to add the rule variable as well to the New-AzFirewallNetworkRuleCollection cmdlet:

$NetRuleCollection = New-AzFirewallNetworkRuleCollection -Name 'fw-rule-collection' -Priority 200 `
   -Rule $NetRule1,$NetRule2 -ActionType "Allow"

When done, I RDP'ed to a VM and went to activation. It wasn't activated. I clicked on troubleshoot and the VM activated. Likely after a while all VMs will activate automatically.

Azure: Create an availability set with two VMs with PowerShell

If you have two or more virtual machines in Azure running in a pair or a cluster (for example domain controllers), you want to make sure that the proper redundancy is in place. Both in regards to separating VMs between datacenters and making sure that during maintenance that MS will not reboot your VMs at the same time. This can be done by creating an availability set which places VMs into availability zones.

An availability zone is the combination of a fault domain (which is a separate physical datacenter within a given region such as West Europe) and an update domain (the underlying hardware 'group', likely the hypervisor. This is to avoid VMs freezing or being rebooted at the same time during a Azure update which can happen on rare occasions according to MS).

The order in which you create the availability set is the following:
  • First you create the availability set
  • Then you create the individual VMs - and the important part is that the availability set has to be specified/set during VM creation using a parameter (AvailabilitySetName). If the VM has already been created without this parameter, then it cannot be added to the availability set later
If you are creating the VMs in PowerShell from scratch an not using the "New-AzVMConfig" cmdlet to specify VM settings in your script, then you can follow this MS guide. However, if you're using "New-AzVMConfig" then it has to be done slightly differently.

Create availability set

# Variables

$ResourceGroupName = "myRG"
$LocationName = "westeurope"
$AvailSetName = "AvailabilitySetAD01"

New-AzAvailabilitySet `
   -Location $LocationName `
   -Name $AvailSetName `
   -ResourceGroupName $ResourceGroupName `
   -Sku aligned `
   -PlatformFaultDomainCount 2 `
   -PlatformUpdateDomainCount 2

This creates the availability set with two fault domains and two update domains. In West Europe you can have up to three fault domains.

To create the VMs, make sure that the following lines are set in the script (copy/paste the snippet to get all the code):

$AvailSetName = "AvailabilitySetAD01"
# Get the availability set for domain controllers
$AvailSet = Get-AzAvailabilitySet -ResourceGroupName $ResourceGroupName -AvailabilitySetName $AvailSetName
# Create new VM config object and add it to the availability set
$VirtualMachine = New-AzVMConfig -VMName $VMName -VMSize $VMSize -AvailabilitySetID $AvailSet.Id

An example of a full VM script including the above three lines can be seen below. If using this in its entirety, make sure that the resource groups, key vault, and storage group are created in advance (or not use the specific parts about key vault and boot diagnostics).

# Update these variables:
# Update to correct RG name
$ResourceGroupName = "ad-RG"
$Vnetrgname = "vnet-RG"
$rgLogmon = "logmon-RG"
$secrgname  = "sec-RG"

$ComputerName = "myServer01" # Change this!
$VMName = "myServer01" # Change this!
$VMSize = "Standard_B2s"
$Vnetname = "MYvnet"
$SubnetName = "MyZone01"
$Disksize = "128"
$OSDiskName = $($VMName) + '-disk01'
$Publisher = "MicrosoftWindowsServer"
$Offer = "WindowsServer"
$Sku = "2019-Datacenter"
$DiskType = "StandardSSD_LRS"
$PrivateIP = "" # Change this!
$stgaccountname = "myStorageAccount"
$kvname = "MyKV"
$secretname = "localadmpwd"
$AvailSetName = "AvailabilitySetAD01"

# Do not update these variables
$VMLocalAdminUser = "localadmin"
# Will prompt for password during deploy
#$VMLocalAdminSecurePassword = ConvertTo-SecureString  -AsPlainText -Force
# Will get password from text file
#$VMLocalAdminSecurePassword = Get-Content ./vmos-sec-key.txt | ConvertTo-SecureString -AsPlainText -Force
# Will retrieve passwd from key vault
$VMLocalAdminSecurePassword = (Get-AzKeyVaultSecret -vaultName $kvname -name $secretname).SecretValueText | ConvertTo-SecureString -AsPlainText -Force
$LocationName = "westeurope"
$NICName = $($VMName) + '-nic01'
$OSDiskName = $($VMName) + '-OsDisk01'

Write-Host "Creating variables at $(Get-Date)"
# Get existing Vnet
$Vnet = Get-AzVirtualNetwork -Name $Vnetname -ResourceGroupName $Vnetrgname
# Get existing subnet
$Subnet = Get-AzVirtualNetworkSubnetConfig -Name $SubnetName -VirtualNetwork $Vnet
# Set static private IP address
$IPconfig = New-AzNetworkInterfaceIpConfig -Name "IPConfig1" -PrivateIpAddressVersion IPv4 -PrivateIpAddress $PrivateIP -SubnetId $Subnet.Id
# Create a new NIC for the VM and associate the private IP
$NIC = New-AzNetworkInterface -Name $NICName -ResourceGroupName $ResourceGroupName -Location $LocationName -IpConfiguration $IPconfig -Force

# Create credentials object
$Credential = New-Object System.Management.Automation.PSCredential ($VMLocalAdminUser$VMLocalAdminSecurePassword);
# Get the availability set for domain controllers
$AvailSet = Get-AzAvailabilitySet -ResourceGroupName $ResourceGroupName -AvailabilitySetName $AvailSetName
# Create new VM config object and add it to the availability set
$VirtualMachine = New-AzVMConfig -VMName $VMName -VMSize $VMSize -AvailabilitySetID $AvailSet.Id
# Set OS type and OS name and add to VM config object
$VirtualMachine = Set-AzVMOperatingSystem -VM $VirtualMachine -Windows -ComputerName $ComputerName -Credential $Credential -ProvisionVMAgent -EnableAutoUpdate
# Associate the NIC with the VM config object
$VirtualMachine = Add-AzVMNetworkInterface -VM $VirtualMachine -Id $NIC.Id
# Specify OS type for the VM config object
$VirtualMachine = Set-AzVMSourceImage -VM $VirtualMachine -PublisherName $Publisher -Offer $Offer -Skus $Sku -Version latest
# Set disk size in GB
$VirtualMachine = Set-AzVMOSDisk -VM $VirtualMachine -DiskSizeInGB $Disksize -Name $OSDiskName -StorageAccountType $DiskType -CreateOption FromImage
# Set storage account for boot diagnostics (udpate line below)
$VirtualMachine = Set-AzVMBootDiagnostic -VM $VirtualMachine -Enable -ResourceGroupName $rgLogmon -StorageAccountName $stgaccountname

Write-Host "Creating new VM...(this can take 10+ minutes). Starting at $(Get-Date)"
# Create the VM using VM config object 
New-AzVM -ResourceGroupName $ResourceGroupName -Location $LocationName -VM $VirtualMachine -Verbose
Write-Host "VM created"
Write-Host "Script done at $(Get-Date)"

When done, it will look like below in the portal: