Configuring AD Sites and Subnets using Puppet

Posted: November 13, 2018 in puppet, Windows Server

I modified this script:

Add-Type -Assembly Microsoft.VisualBasic
$dc = ($env:logonserver).SubString(2)
$sitesPath = "CN=Sites,CN=Configuration," + (Get-ADDomain).DistinguishedName
$logPath = "C:\Script\logs\"
#$fileDate = get-filedate
#$fileNameBig = "import-sites_" + $env:username + "_" + $fileDate + ".log"
$fileNameBig = "CreateADSIte" + ".log"
$fileNameSmall = "ADSites" + ".JSON"
$logFileBig = $logPath + $fileNameBig
$logFileSmall = $logPath + $fileNameSmall

function init-log {
if((Test-Path $logPath) -eq $false) {
Write-Host ("Creating log folder " + $logpath + "...") -ForegroundColor "Yellow"
try {
New-Item -ItemType Directory -Path $logPath -ErrorAction Stop | Out-Null
}
catch {
Write-Warning ("Log path (" + $logPath + ") could not be created! Please change variable!")
Exit
}
Write-Host ("Log folder successfully created.") -ForegroundColor "Green"
}
if((Test-Path $logFileBig) -eq $false) {
$date = Get-Date
Write-Host ("Creating log file " + $logFileBig + "...") -ForegroundColor "Yellow"
try {
"Date: " + $date | Out-File -Append -Encoding UTF8 -FilePath $logFileBig -ErrorAction Stop
}
catch {
Write-Warning "Could not write to log file (" + $logFileBig + ") Please check!"
Exit
}
Write-Host ("Log file successfully created.") -ForegroundColor "Green"
#("UserName: " + $env:username) | Out-File -Append -Encoding UTF8 -FilePath $logFileBig
Out-File -Append -Encoding UTF8 -FilePath $logFileBig
("Log file: " + $logFileBig) | Out-File -Append -Encoding UTF8 -FilePath $logFileBig
}
}

function get-subnetAD {
param($subnet)

$ldapFilterSubnet = "(&(objectCategory=subnet)(objectClass=subnet)(name=" + $subnet + "))"
$subnetAD = Get-ADObject -LDAPFilter $ldapFilterSubnet -SearchBase $sitesPath -Server $dc -Properties siteObject, location
return $subnetAD
}

function remove-newlines {
param($string)

$string = $string = ($string.Replace("`n"," ")).Replace("`r","")
return $string
}

function get-siteAD {
param($siteName)

$ldapFilterSite = "(&(objectClass=site)(objectCategory=site)(name=" + $siteName + "))"
$siteAD = Get-ADObject -LDAPFilter $ldapFilterSite -SearchBase $sitesPath -Server $dc -Properties location
return $siteAD
}

function get-filedate {
$date = Get-Date
$year = (($date.Year).ToString()).SubString(2,2)
if($date.Month -lt 10) {
$month = "0" + $date.Month
}
else {
$month = ($date.Month).ToString()
}
if($date.Day -lt 10) {
$day = "0" + ($date.Day).ToString()
}
else {
$day = $date.Day
}

$fileDate = $year + $month + $day

return $fileDate
}

function create-site {
param($siteName,
$location)

$ldapFilterSite = "(&(objectClass=site)(objectCategory=site)(name=" + $siteName + "))"
$siteAD = Get-ADObject -LDAPFilter $ldapFilterSite -SearchBase $sitesPath -Server $dc
if($siteAD -eq $null) {
try {
$siteAD = New-ADReplicationSite -Name $siteName -Server $dc -PassThru -ErrorAction Stop
}
catch {
log-write ("ADReplicationSite " + $siteName + " could not be created. Reason: " + $_.Exception.Message) -foregroundColor "warn"
return $null
}

try {
#$siteAD = Set-ADReplicationSite -Identity $siteAD -Add @{location=$location} -Server $dc -ErrorAction Stop -PassThru
$siteAD = Set-ADReplicationSite -Identity $siteAD -Server $dc -ErrorAction Stop -PassThru
}
catch {
log-write ("ADReplicationSite " + $siteAD.Name + " could not be set. Reason: " + $_.Exception.Message) -foregroundColor "warn"
}
}
return $siteAD
}

function create-subnet {
param($subnet,
$siteAD)
#$location)

try {
$subnetAD = New-ADReplicationSubnet -Name $subnet -Site $siteAD -Location $location -Server $dc -ErrorAction Stop -PassThru
#$subnetAD = New-ADReplicationSubnet -Name $subnet -Site $siteAD -Server $dc -ErrorAction Stop -PassThru
}
catch {
log-write ("ADReplicationSubnet " + $subnet + " could not be created. Reason: " + $_.Exception.Message) -foregroundColor "warn"
return $null
}
return $subnetAD
}

function log-write {
param([String]$output,
$foregroundColor,
$backgroundColor)

#$timeStamp = get-timestamp

$output = $output

if($foregroundColor -ieq "warn") {
Write-Warning $output
}
else {
if(($backgroundColor -eq $null) -and ($foregroundColor -eq $null)) {
Write-Host $output
}
if(($backgroundColor -eq $null) -and ($foregroundColor -ne $null)) {
Write-Host $output -ForegroundColor $foregroundColor
}
if(($backgroundColor -ne $null) -and ($foregroundColor -eq $null)) {
Write-Host $output -BackgroundColor $backgroundColor
}
if(($backgroundColor -ne $null) -and ($foregroundColor -ne $null)) {
Write-Host $output -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
}
}
try {
$output | Out-File -Append -Encoding UTF8 -FilePath $logFileBig -ErrorAction Stop
}
catch {
Write-Warning "Error writing to log file!!"
Write-Host $_.Exception.Message
}
}

function get-subnetMask {
param($subnet)

if(($subnet -eq $null) -or ($subnet -eq [String]::Empty)) {
return $null
}
$subnetMask = 0
$array = $subnet.Split(".")
foreach($octet in $array) {
if([Microsoft.VisualBasic.Information]::IsNumeric($octet)) {
$charArray = ([Convert]::ToString($octet,2)).ToCharArray()
foreach($bit in $charArray) {
$subnetMask += $bit.ToString()
}
}
else {
return $null
}
}
return $subnetMask
}

init-log

$CONFIGDATA = Get-Content -Path "C:\AD\Sites.json" | ConvertFrom-JSON

foreach($network in $CONFIGDATA)
{
$network | Add-Member NoteProperty "ADSite" $null
$subnetMask = get-subnetMask $network.Subnet
$subnet = $network.NetworkAddress + "/" + $subnetMask
$adsite=$network.SiteName

if(($network.SiteName -ne $null) -and ($network.SiteName -ne [String]::Empty)) {
$network.SiteName = remove-newlines $network.SiteName
}

$siteAD = get-siteAD $adsite

if($siteAD -eq $null) {
log-write ("Site " + $adsite + " could not be found. Creating site...") -foregroundColor "Yellow"
$siteAD = create-site $adsite
if($siteAD -eq $null) {
log-write ("Site " + $adsite + " could not be created!") -foregroundColor "warn"
#$network.SiteStatus = "Error"
export $network
continue
}
else {
log-write ("Site " + $adsite + " was successfully created") -foregroundColor "Green"
#$network.SiteStatus = "OK"
}
}

$subnetAD = get-subnetAD $subnet
if($subnetAD -eq $null) {
log-write ("Subnet could not be found in AD. Attempting to create it...") -foregroundColor "Yellow"
$subnetAD = create-subnet $subnet $siteAD
if($subnetAD -ne $null) {
log-write ("Subnet successfully created.") -foregroundColor "Green"
#$network.SubnetStatus = "OK"
}
else {
log-write ("Subnet could not be created") -foregroundColor "warn"
#$network.SubnetStatus = "Error"
#export $network
continue
}
}

}

Script above will read content of ADSites.JSON file

[
  {
    "NetworkAddress": "10.140.40.0",
    "Subnet": "255.255.252.0",
    "SiteName": "CTA001"
  },
  {
    "NetworkAddress": "10.83.0.0",
    "Subnet": "255.255.0.0",
    "SiteName": "CTA001"
  },
  {
    "NetworkAddress": "10.196.112.0",
    "Subnet": "255.255.252.0",
    "SiteName": "CTA001"
  },
  {
    "NetworkAddress": "10.196.136.0",
    "Subnet": "255.255.252.0",
    "SiteName": "CTA002"
  }
]

Script will create subnets specified in JSON file and associate it to corresponding AD site.
Puppet manifest file will create C:\AD if it doesn’t exist, will copy JSON and ps1 file from /opt/puppetfiles/  in Puppet server to C:\AD on windows node and will execute createsite.ps1 script (Script will be executed only if C:\AD\logs doesn’t exist or if log file has Subnet successfully created string.

#Create C:\Script\ directory
file {

['c:/Script/']:

ensure => directory,
}

# copy JSON file with AD Site names and subnets

file { 'c:\Script\ADSites.json':
ensure => present,
content => file('/opt/puppetfiles/ADSites.json'),
}

# copy Script

file { 'c:\Script\createsite.ps1':
ensure => present,
content => file('/opt/puppetfiles/createsite.ps1'),
}

#Execute powershell script on Windows node (run it only if log files doesn't contain "Subnet successfully created"
#string
exec { 'Create sites':
command => 'C:\Script\createsite.ps1',
unless => 'if (!(Test-Path C:\Script\logs\CreateADSite.log) -or !(Select-String -Path C:\Script\logs\CreateADSite.log -Pattern "Subnet successfully created")) {exit 1}',
provider => powershell,
logoutput => true,
}

 

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s