DeployVM

This scripts deploys a VM

ps: please note : I’m no Powershell guru and don’t have much powershell experience yet. These scripts is not nice and clean but it does the job…
I’m no powershell script guru , so this script will hurt the real Powershell guys but I decided to post it anyway.

Param($MyVM,$requestType,$requestOS,$login,$IP);
cls
# example of this command : .\uzlvmRequestVM.ps1 -MyVM "erikschils" -requestType "Crosscluster"-requestOS "2003" -login "eriks"

Write-Host "Starting with script to Deploy VM"

function checksnapin(){
#
#
# Add in Snapins Before launching Script.  I’ve written this, so you could run a pile of these checks
# and until it’s all ‘GOOD’ the script will quickly fail out.
#
#
# Variable to remember the $STATUS of your modules loaded
$STATUSLOADED=$FALSE 

# The name of whatever snapin being dealt with
$SNAPIN='VMware.VimAutomation.Core' 

# Try to add the Snapin and be VEWY QWIET if it DOESN’T load 😉
#
ADD-PSSNAPIN $SNAPIN –erroraction SilentlyContinue
#
# Check to see if it successfully loaded
#
IF ((GET-PSSNAPIN $SNAPIN) –eq $NULL)
     {
          # If not loaded – Notify user with required details
          #
         write-host "This script required POWERCLI from vmware"

     }
ELSE
    {
          # If it DID, Flag Status as GOOD
          #
          $STATUSLOADED=$TRUE
     }
# And we treat the WHOLE script as an “IF” to make it work only “IF”
# the require modules have been loaded!
#
}

function DeployVM(){
#defining default values for networkadapter
$Subnetmask = "255.255.255.0"
$DNS1 = "22.22.22.22"
$DNS2 = "22.22.22.3"
$WINS1 = "22.22.22.1"
$WINS2 = "22.22.22.2"
$message = "`r`nVM:$MyVM`r`nRequested By: $login`r`nIP : $IPAddress"

# Find the least used host in that cluster
$HostLeastBusy = Get-cluster -Name "$OriginalCluster" | Get-VMHost -State Connected | Sort $_.CPuUsageMhz -Descending | Select -First 1

# Find a datastore on that host with enough room
$strDatastore = $HostLeastBusy | Get-Datastore | Where-Object -FilterScript {$_.Name -notmatch "nucleus|diest|datastore|iso|nosnapshot"} | Sort-Object -Descending -Property FreeSpaceMB | Select-Object -Property Name -First 1
$maxDatastore = Get-Datastore $strDatastore.Name

 $currentTime= Get-Date
 # notify user of best placement location
$message += "`r`nBest Placed on HostLeastBusy: $HostLeastBusy (ESXcluster: $requestType) `r`nStorage $maxDatastore with most free space`r`nDeployment Started ($currentTime)`r`nTemplate : $Template`r`nVLAN: $VLAN ($VLANlabel with Gateway : $DefaultGW)"
$Mailsubject = "Starting Deployment of $MyVM with IP $IPAddress - ESXcluster: $requestType -  Requested by : $login"
Send-MailMessage –From "erik.schils@gmail.com" –To "$login@blahblah.be" -Cc "erik.schils@gmail.com" –Subject "$Mailsubject" -Body "$Mailsubject" –SmtpServer "exchange.blahblah.be"

Get-OSCustomizationSpec $Customization | Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping -IpMode UseStaticIp -IpAddress $IPAddress -SubnetMask $Subnetmask -DefaultGateway $DefaultGW -Dns $DNS1,$DNS2 -Wins $WINS1,$WINS2 

#deploy vm with all information
New-VM -Name $MyVM -Template $(get-template $Template) -VMHost $HostLeastBusy -Datastore $maxDatastore -DiskStorageFormat Thin -OSCustomizationSpec $(Get-OSCustomizationSpec $Customization)

Get-NetworkAdapter $MyVM | Set-NetworkAdapter -NetworkName $VLANlabel -Confirm:$false

#set the login on field resplogin1 so we know who the owner of the vm is
Get-VM -Name "$MyVM" | Set-Annotation -CustomAttribute "ownerSO" -Value $login

 $currentTime= Get-Date
$message += "`r`nVM Powering Up ($currentTime)"
Write-Host "$message"
$finalresult = Start-VM -VM $MyVM
$finalresult

# ready notify user and mail
$message += "`r`n`r`n`r`nVM Ready But give me some time(approx 10 minutes) to customize... `r`n"
$message += "`r`n`r`n`r`nDo NOT forget to change this setting : http://wiki/x/eQI4CQ  `r`n"

$Mailsubject = "$message"
Send-MailMessage –From "erik.schils@gmail.com" –To "$login@blahblah.be" -Cc "erik.schils@gmail.com" –Subject "$MyVM deployed - $MyVM,$Template,$Customization,$Clustername,$IPAddress" -Body "$message" –SmtpServer "exchange.blahblah.be"

}

function CreateSSHKey ()
{
      $key = Get-Content -Path \\fileserver\data\software\PS\Admin\Scripts\VMWARE\vmaanvraag\sshkey.txt
      New-Item 'HKCU:\Software\SimonTatham' -ErrorAction SilentlyContinue
      New-Item 'HKCU:\Software\SimonTatham\PuTTY' -ErrorAction SilentlyContinue
      New-Item 'HKCU:\Software\SimonTatham\PuTTY\SshHostKeys' -ErrorAction SilentlyContinue
      Set-ItemProperty 'HKCU:\Software\SimonTatham\PuTTY\SshHostKeys' -Name 'yoypoypyopypy' -Value $key  -ErrorAction SilentlyContinue
}

##############################################################
##############################################################
##############################################################
##############################################################
#
# Begin SCRIPT
#
##############################################################
##############################################################
##############################################################

checksnapin

#Connect-VIServer $vc -SaveCredentials
$vc = "vCenter5"

Connect-VIServer $vc

# predefined values for testing script but need to be filled in automagically
#$requestType= "Crosscluster"
#$Global:MyVM = "erikschils"
#$requestOS = "2008"

#if ($MyVM -match '')
#{
#Write-Host "Stopped... some Parameters are missing"
#Exit
#End
#}

#defining default values for template and customization
$strTemplate2003 = "w2k3stdwsp2_vi5"
$strTemplate2008 = "w2k8stdr2_sp1_vi5"
$strTemplate2008SQL = "w2k8r2_std_sql"
$strTemplate2008std32bit ="w2k8_std_x86_sp1"

$strCustomSpec2008 = "server2008_auto"
$strCustomSpec2003 = "server2003_auto"

# according to the Requestype we define the VLANlabel,VLAN, Crosscluster
#CrossCluster ,PlayCluster,BroerZusAzuurCluster,BroerZusPewterCluster,DataBaseAzuurCluster,DataBasePewterCluster,DMZCluster

if ($requestType -eq "Crosscluster" -or $requestType -eq "PlayCluster" -or $requestType -eq "DataBaseAzuurCluster" -or $requestType -eq "DataBasePewterCluster")
{
$VLAN = "3663"
$VLANlabel = "vlan3663_vmserver"
$Global:DefaultGW = "0.254.63.254"
}
elseif ($requestType -eq "BroerZusAzuurCluster")
{
$VLAN = "3785"
$VLANlabel = "vlan3785_broer"
$Global:DefaultGW = "0.254.185.254"
}
elseif ($requestType -eq "BroerZusPewterCluster")
{
$VLAN = "3850"
$VLANlabel = "vlan3850_zus"
$Global:DefaultGW = "0.254.250.254"
}
elseif ($requestType -eq "DMZCluster")
{
$VLAN = "3663"
$VLANlabel = "vlan3663_vmserver"
$Global:DefaultGW = "0.254.63.254"
}
else
{
$VLAN = "3663"
$VLANlabel = "vlan3663_vmserver"
$Global:DefaultGW = "0.254.63.254"
}

#clusterinfo
$cluster = get-cluster -Name $requestType
$Global:OriginalCluster = $cluster.name

# check OS and set template accordingly
if ($requestOS -match "2003")
{
$Global:Customization = $strCustomSpec2003
$Global:Template = Get-Template $strTemplate2003
}
elseif ($requestOS -match "2008R2withSQL2008")
{
$Global:Customization = $strCustomSpec2008
$Global:Template = Get-Template $strTemplate2008SQL
}
elseif ($requestOS -match "2008STD32bit")
{
$Global:Customization = $strCustomSpec2008
$Global:Template = Get-Template $strTemplate2008std32bit
}
else
{
$Global:Customization = $strCustomSpec2008
$Global:Template = Get-Template $strTemplate2008
}

$result = ""
if($IP -contains ".")
{

}
else{
CreateSSHKey
$cmd = "\\uz\data\software\PS\Admin\Scripts\VMWARE\vmaanvraag\plink.exe -batch -i \\uz\data\software\PS\Admin\Scripts\VMWARE\vmaanvraag\sleutel.ppk -l www-data laurel /etc/bind/voegnaamtoeinvlan $MyVM $VLAN"
$result = Invoke-Expression -Command $cmd -ErrorAction continue
Write-Host "result : $result"
$IP = "$result"
}

# set fixed ipaddress to test my script
$Global:IPAddress = "$IP"

Write-Host $cmd

if ($IP -match 'gekoppeld')
{
Send-MailMessage –From "erik.schils@gmail.com" –To "$login@uzleuven.be" -Cc "erik.schils@gmail.com" –Subject "$MyVM - ALREADY IN DNS - $MyVM,$Template,$Customization,$Clustername,$IPAddress" -Body "please check DNS, a dnsentry already exists with that name : $IP or close the VM Request" –SmtpServer "exchange.blahblah.be"
exit
}
else{
#run Deploy VM

$lastdigits = $IP.split(".")[3]
$Numberlast3digits = $lastdigits -as [int]
Write-Host "Last 3 digits : $Numberlast3digits"

if ($Numberlast3digits -gt 200){
Write-Host "Warning: Treshold above 200"
Send-MailMessage  –From "erik.schils@gmail.com" –To "erik.schils@gmail.com" –Subject "Warning. Ipnumber $MyVM is above 200 ($IPAddress) - $last3digits" -Body "Time to check available leases or create new VLAN" –SmtpServer "exchange.blahblah.be"
}

Write-Host "Last 3 digits : $Numberlast3digits"
Write-Host "ready set go..."
DeployVM
}

##############################################################
##############################################################
##############################################################
##############################################################
#
# END SCRIPT
#
##############################################################
##############################################################
##############################################################

# SIG # Begin signature block

Be the first to comment

Leave a Reply

Your email address will not be published.


*