Scripts

Export/Import vCloud Director 5.1 OrgNetworks with PowerCLI

I decided to provide an extension on the last post I did, Creating OrgNetworks in vCloud Director 5.1 with PowerCLI.  I had a need for being able to export OrgNetworks from a vCD 5.1 environment and be able to replicate/rebuild/recreate the OrgNetworks from the exported list.  Due to this need I attempted to create a PowerCLI script to do this for me.  Here is what I came up with, mind you it isn’t the sexiest script in the world but it worked for my needs and can be easily adjusted to fit yours.   Continue reading “Export/Import vCloud Director 5.1 OrgNetworks with PowerCLI” »

Create OrgNetworks in vCloud Director 5.1 with PowerCLI

So I know I haven’t posted in a little while anything truly useful…well, hopefully, that changes with this one.  I was approached by a colleague with a need for creating OrgNetworks with PowerCLI.  Knowing that things changed from earlier versions when you could create new OrgNetworks with New-OrgNetwork in vCD 1.5, I needed to see how to do it the new way with Cloud Views.  So first, let’s look at what information we need in order to make this work:

Script: Track-Datastores.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#Global Functions
#This function generates a nice HTML output that uses CSS for style formatting.
function Generate-Report {
    Write-Output "<html><head><title></title><style type=""text/css"">.Error {color:#FF0000;font-weight: bold;}.Title {background: #0077D4;color: #FFFFFF;text-align:center;font-weight: bold;}.Normal-left {text-align:left;}.Normal {text-align:center;}</style></head><body><table><tr class=""Title""><td colspan=""3"">  VMware Datastore Change Report  </td></tr><tr class="Title"><td>Datastore</td><td>  Difference(MB)  </td><td>  % Free  </td></tr>"
 
                Foreach ($line in $myColDiff){
                    Write-Output "<td class=""Normal-left"">$($line.name)</td><td class=""Normal"">$($line.Diff)</td><td class=""Normal"">$($line.PercentFree)</td></tr> "
                }
        Write-Output "</table></body></html>"
    }
   
# Variables #
#############

$VIServer = "VISERVER"
$username = "changeme"
$password = "supersecret"
$digits = 2
$Folder = 'C:\Reports'
$currentFile = 'Datastores_Current.xml'
$previousFile = 'Datastores_Previous.xml'

# Script #
##########

# First, if a Current file exists, rename this Current file to Previous

If (Test-Path "$Folder\$currentFile")
{
    Remove-Item -Path "$Folder\$previousFile" -Force
    Rename-Item -Path "$Folder\$currentFile" -NewName $previousFile
}

# Next, let's measure and save current datastore sizes

# Connect to Virtual Center
$VC = Connect-VIServer $VIServer -user $username -password $password

# Get all datastores and put them in alphabetical order
$datastores = Get-Datastore | Sort-Object Name

# Create an array to hold the output
$myColCurrent = @()

# Loop through datastores
ForEach ($store in $datastores)
{
    # Create a custom object and define its properties
    $myObj = "" | Select-Object Name, CapacityGB, UsedGB, PercFree
    # Set the values of each property
    $myObj.Name = $store.name
    $myObj.CapacityGB = [math]::Round($store.capacityMB/1024,$digits)
    $myObj.UsedGB = [math]::Round(($store.CapacityMB - $store.FreeSpaceMB)/1024,$digits)
    $myObj.PercFree = [math]::Round(100*$store.FreeSpaceMB/$store.CapacityMB,$digits)
    # Add the object to the output array
    $myColCurrent += $myObj
}

# Export the output to an xml file; the new Current file
$myColCurrent | Export-Clixml -Path "$Folder\$currentFile"

# Disconnect from Virtual Center
Disconnect-VIServer -Confirm:$False

# Finally, let's compare the Current information to that in the Previous file

# Check if a Previous file exists
If (Test-Path "$Folder\$previousFile")
{
    # Import the Previous file
    $myColPrevious = Import-Clixml "$Folder\$previousFile"
    # Create an array to hold the differences
    $myColDiff = @()
    # Loop through the current datastores
    ForEach ($myObjCurrent in $myColCurrent)
    {
        # The actual compare command
        $diff = Compare-Object ($myColPrevious | Where { $_.Name -eq $myObjCurrent.Name }) $myObjCurrent -Property PercFree
        # In case of any differences, try to get specifics
        If ($diff)
        {
            # Again, a custom object and properties for outputting results
            $myObjDiff = "" | Select-Object Name, PercentFree, Diff
            # Again, setting the values of each property
            $myObjDiff.Name = $myObjCurrent.Name
            $myObjDiff.PercentFree = $myObjCurrent.PercFree
            # The most important property is the calculated difference between the current and previous values of PercFree. You can substitute it for UsedGB if you like.
            $myObjDiff.Diff = ($diff | Where { $_.SideIndicator -eq '=>' }).PercFree - ($diff | Where { $_.SideIndicator -eq '<=' }).PercFree
            # And agin, adding it to the output array
            $myColDiff += $myObjDiff
        }
        # Clearing the variable used inside the loop to prevent incorrect output in case of problems setting the variable!
        Clear-Variable diff -ErrorAction "SilentlyContinue"
    }
    # If nothing changed, we don't want an empty file.
    If ($myColDiff.Length -eq 0)
    {
        $myColDiff = "No changes since last check."
    }
    # And we conclude by outputting the results to a text file, which can be emailed or printed.
    Generate-Report > "$Folder\Track-Datastore.html"
}

IF ($myColDiff -ne "No changes since last check."){
    $SmtpClient = New-Object system.net.mail.smtpClient
    $SmtpClient.host = "my.smtp.host"   #Change to a SMTP server in your environment
    $MailMessage = New-Object system.net.mail.mailmessage
    $MailMessage.from = "System.Automation@example.com"   #Change to email address you want emails to be coming from
    $MailMessage.To.add("yomomma@example.com")  #Change to email address you would like to receive emails.
    $MailMessage.IsBodyHtml = 1
    $MailMessage.Subject = "VMware Datastore Change Report"
    $MailMessage.Body = Generate-Report
    $SmtpClient.Send($MailMessage)}

ESXi 5.0 and APC SmartUPS 1000

So the company I work for had a deployment scenario in place for there remote branches utilizing VMware Server 2 prior to me coming onboard.  I was tasked with the redesign of our remote branch virtualization infrastructure.  In comes ESXi 5.0 to replace the fading away VMware Server.  Initially they were using a software-based RAID which was controlled through a SLES installation.  With the requirements of ESXi we all know that software RAID is not an option.  We have since decided on utilizing an Adaptec 2405 RAID controller for these remote servers.  Now that my test lab can boot into ESXi I can move forward with the remaining requirements.

 

Clean Shutdown of VMs and Host

In order for us to have the ability to interface with the APC SmartUPS 1000′s that we have at each location for the server we must find a way to install the APC PowerChute Business Edition Agent (PCBEAgent) for use with monitoring and shutting down the host and VMs.  In comes the vSphere Management Assistant (vMA).

Please note that this setup IS NOT a supported solution by either VMware or APC. Use of this method is at the sole discretion of the admin and the teams supporting the sites!

In order to install the APC PCBEAgent, we needed either a Linux VM or a Windows VM.  In the light of trying to architect a solution that minimizes costs and addition of other hardware, we selected a Linux VM or in this case the vMA.  The vMA is a SLES4VMware-based appliance and therefore gives us the ability to build or install agents accordingly.  Finally, we just grabbed the installer from APC for the RPM which could be installed on the vMA.  Installation on the vMA was simple:

# rpm -ivh pbeagent-xxx.i386.rpm

This placed the PBEAgent in /opt/APC/PowerChuteBusinessEdition/Agent.  This will also install the startup script in /etc/init.d.  Once it is installed you will need to do the initial configuration by running the config.sh script from within the aforementioned directory.  This will allow you to setup the administrative username and password to login and control the agent from the webUI that the agent starts.  After you have configured it should start the agent, if not, just start the agent manually.  The startup script is PBEAgent and can be started via /etc/init.d/PBEAgent start.  Once you start the agent you can connect to it via https://<vMA-IP>:6547.  Once you are in the webUI you will notice that there is no communication with the APC unit.  Here brings us into the next step, configure Serial Passthrough on the vMA appliance.

 

Serial Passthrough on the vMA Appliance

In order to configure Serial Passthrough you must power down the vMA appliance.  Once you have powered down the vMA appliance you can add the Serial Port interface on the VM.  You will select the “Use physical port” option and it should show a device similar to this:  /dev/char/serial/uart0

Once this is done power your vMA appliance back on and connect to the PBEAgent webUI.  Make sure that you have the APC SmartUPS serial cable connected.  It is important to note that you MUST use the provided cable as the pinout is special.  From here you will need to configure the UPS.  You will want to select “Server Shutdown” option on the left side and then select “System Settings”.  Here you will be presented with the options for the signaling type (Smart/Simple/Simple with Interface Expander).  You will want to select Smart and for the port use /dev/sttyS0.  Once you have done this select the “Smart-UPS 1000″ option on the left side to view the status.  If everything was done correctly you should see the Device Status as On line and some other information on the status page.

 

Configure Server Shutdown Script

Now that we have the proper communication with the UPS and the vMA we need to configure the shutdown script to execute accordingly when we either reach a specified threshold for battery power or as soon as the unit senses loss of power.  I will not go into the details of how to select or configure each but feel free to sound off in the comments if you need help.  All of the scripts or “cmdfiles” (as APC calls them) are located in /opt/APC/PowerChuteBusinessEdition/Agent/cmdfiles.  I have created a simple script that utilizes the vCLI SDK.  Here is the script:

1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/sh
#
# VmShutdown.sh - Script to gracefully shutdown VMs and Host
#

# Shutdown Guest VMs
/usr/lib/vmware-vcli/apps/vm/vmcontrol.pl --username root --password password --operation shutdown --vmname TESTVM01 --url https://<esxiHostNameOrIP>/sdk/webService

sleep 300  # Change this to a value that suits your environment

# Shutdown ESXi Host
/usr/bin/vicfg-hostops --server --username root --password password --operation shutdown --force --url https://<esxiHostNameOrIP>/sdk/webService

The script can be expanded upon to fit your needs but for the sake of simplicity I have only regarded a single VM and the host itself.  The script must be chmod’d for execution which can be done via chmod 755 /opt/APC/PowerChuteBusinessEdition/Agent/cmdfiles/VmShutdown.sh.

 

Configure the cmdfile within the PBEAgent

Login back into your PBEAgent webUI.  From here select “Events” on the left side and then select “Actions”.  You will be presented with a long list of Event Actions.  You will want to make sure that the events you want to execute shutdown on are showing that shutdown is selected for the event.

Next we will configure the Shutdown Settings to utilize this cmdfile.  Select “Server Shutdown” on the left side and then “Shutdown Settings”.  You are then presented with the Shutdown Sequence Summary.  At the bottom you can click on “Configure”.  Click Configure and then scroll to the bottom where you can see “Command File”.  Check the checkbox and from the dropdown, select the script to execute.  I have configured a file execution duration of 2 minutes to allow for the script to execute fully before the vMA gets shutdown by the PBEAgent itself.  You can adjust this to your liking depending on the need and amount of VMs on the single host.  Once you have configured this, click on “Apply”.

 

Fin

This concludes the configuration of the PBEAgent for use on an ESXi standalone host.  This should now allow for a clean shutdown of both your VMs and the ESXi host itself.  It you have any questions then please sound off in the comments below!  Have fun!

1 2 3  Scroll to top