RSS .92| RSS 2.0| ATOM 0.3
  • Home
  •  

    PowerCLI: Add VM’s in vApp, within vCloud Directory to Security Groups withing vShield App

    October 3rd, 2012

    The title says it all!  The use case:

    You are using vCloud Director, and want to add Virtual Machines from deployed vApps to specific Security Groups within vShield App.  In my case, there were three Security Groups created to make a 3-tier environment.  Web, App and Database.

    Once again Alan Renouf came through by creating a vShield module for PowerCLI.  Follow the directions in his video to install it.  It’s actually quite easy.

    The script I am going to list below requires valid connections to three sources in order to do the work:

    1. The vCenter that manages the compute nodes in your vCloud
    2. The vCloud Director cell.
    3. The vShield Manager for the vCloud stack.

    (You also need to be licensed for vShield App.)

    Prior to connecting to vShield Manager, you will need to instantiate the module Alan created.  That _should_ have been done when watching his video, but if not, do:

    import-module vshield

    within PowerCLI.

    At this point you can connect to your three services:

    • connect-viserver <for vCenter>
    • connect-ciserver <for vCloud Director>
    • connect-vshieldserver <for vShield Manager>

    Ok, so now hopefully our connections are set up.  Let’s describe the script a little more.  As I said before, the use case was to create a 3-tier environment via vShield App: Web, App and DB.  Our VM’s in the vApp are conveniently named “WWW,” “APP” or “DB.”  We are sort of cheating, and keying off that nomenclature to identify the VM’s.

    We have three hardcoded security groups in the script: Web, App and DB.  Their variables are $SGWeb, $SGApp and $SGDb.  I know I am clever.

    We are going to provide the name of a vAPP in vCloud Director from the command line.  This script will then walk the contents of the vApp, which are our three servers.  For those who are heavily involved in vCloud Director, you know that each VM in vCenter is identified by <VMNAME> (vCloud UUID).  In order for us to add a VM to vShield App, which is tied to vCenter, we must actually push that naming nomenclature.  I’m frankly not the best at coding, so I had to cheat and use the trim() function twice in order to pull the UUID out of the urn:vcloud:vm:uuid string.

    At that point, we use PowerShell’s like function to do string comparison, and then run Mr. Renouf’s set-vshieldsecuritygroup in order to place the VM in to appropriate vShield App Security Group.  That command is covered in his movie.  I hope you find it useful!

    Usage: ./<scriptname>.ps1 -vapp <vAPP name in vCD> -datacenter <the datacenter object where your vCD and vShield are attached>

    param (
     [string]
     $vApp
     ,
     [string]
     $dataCenter
     )
    
    # Hardcode Security Groups, for now
    $SGWeb = "Web"
    $SGApp = "App"
    $SGDb = "DB"
    
     Foreach ($VM in (get-CIVM -vapp $vApp)) {
    
     $vCloudVM = $VM.name
     write-host "VM name: " $vCloudVM
     $vCloudID = $VM.id
     write-host "vCloud ID: " $vCloudID
     # for whatever reason the trim() function cuts off too much
     # so I had to trim twice. beats me why...
     $vCloudIDtrim = ($vCloudID).trim("urn:vcloud:")
     $vCloudIDtrim = ($vCloudIDtrim).trim("m:")
     write-host "Trimmed vCloud ID: " $vCloudIDtrim
    
     if ($vCloudVM -like '*www*'){
     write-host "Adding $vCloudVM to Security Group $SGWeb..."
     # add VM to SecurityGroup
     set-vShieldSecurityGroup -Add -Datacenter (get-Datacenter $dataCenter) -SecurityGroup $SGWeb -VM (Get-VM "$vCloudVM ($vCloudIDtrim)")
     }
     elseif ($vCloudVM -like '*app*') {
     write-host "Adding $vCloudVM to Security Group $SGApp ..."
     # add VM to SecurityGroup
     set-vShieldSecurityGroup -Add -Datacenter (get-Datacenter $dataCenter) -SecurityGroup $SGApp -VM (Get-VM "$vCloudVM ($vCloudIDtrim)")
     }
     elseif ($vCloudVM -like '*db*') {
     write-host "Adding $vCloudVM to Security Group $SGDb ..."
     # add VM to SecurityGroup
     set-vShieldSecurityGroup -Add -Datacenter (get-Datacenter $dataCenter) -SecurityGroup $SGDb -VM (Get-VM "$vCloudVM ($vCloudIDtrim)")
     }
     }
    

    The output will be of the form:

    VM Name: www001
    vCloudID: urn:vcloud:vm:<UUID>
    Trimmed vCloudID: <UUID>
    Adding www001 to Security Group Web …

    ID : securitygroup-nn
    Datacenter : datacenter
    Member : @{name=www001 (<UUID>); object
    TypeName=VirtualMachine; objectId=<moref>}
    Description :
    Name : Web


    PowerCLI – Disable Host in vCloud Director and place host in Maintenance mode

    September 24th, 2012

    Since I am heavily involved in a vCloud deployment, I have asked many many VMware employees how we can make it easier for our operations staff conduct maintenance on an ESXi server.  As you may or may not know, an ESXi host that is prepared and being used by vCloud Director should be disabled and all virtual machines migrated off prior to maintenance.  In order to accomplish this action, a host must be disabled in vCloud Director, and then placed in to maintenance mode in vCenter.  Two separate interfaces.

    I met Alan Renouf after his PowerCLI session at VMworld 2012, and asked him if he knew of a way to disable a host via PowerCLI.  And he did!  Alan has created a function to conduct enable and disable operations.  He gave me permission to include it in the following code I built as a wrapper to conduct the operation from a command line via PowerCLI.

    Requirements:

    1. PowerCLI installed with the vCloud Director cmdlets.  This is an option at install time, and is disabled by default (for whatever reason).
    2. vCloud Director (naturally)
    3. My script.
    First start PowerCLI.

    In order to connect to vCloud Director, first instantiate a connection via

    Connect-CIServer <vCloud Director cell>

    Start a session to the vCenter server that manages the vCloud pod via

    connect-VIServer <vCenter server>

    Now run the script.  There are two options from the command line -server <ESXi server name> and -state <enable/disable>.

    An example run would be: ./conductMaintenanceVCD.ps1 -server esxi001 -state disable

    Watch vCD and vCenter and be wowed.  Thanks again to Alan for creating the Disable-CIHost and Enable-CIHost functions!

    param (
     [string]
     $server
     ,
     [ValidateSet("enable","disable")]
     [string]
     $state
     )</pre>
    ## Enable/Disable-CIHost function provided by Alan Renouf
     Function Disable-CIHost {
     Param (
     $CIHost
     )
     Process {
     $Search = Search-cloud -QueryType Host -Name $CIHost
     #$HostEXT = $search.ExtensionData
     $HostEXT = $Search | Get-CIView
    
     # Disable the host in vCloud Director
     if ($HostEXT.Enable) {
     $HostEXT.Disable()
     }
     }
    }
    
    Function Enable-CIHost {
     Param (
     $CIHost
     )
     Process {
     $Search = Search-cloud -QueryType Host -Name $CIHost
     #$HostEXT = $search.ExtensionData
     $HostEXT = $search | Get-CIView
    
     # Disable the host in vCloud Director
     if ($HostEXT.Disable) {
     $HostEXT.Enable()
     }
     }
    }
    
    # conduct work on input
    write-host "Conducting $state operation on $server..."
    
    if ($state -eq "enable"){
    
     $serverState = get-vmhost $server
     if ( $serverState.ConnectionState -eq "Maintenance") {
     write-host "Taking $server out of maintenance mode"
    
     $returnCode = set-VMhost -VMHost $server -State Connected
    
     # sleep for 45 seconds for the host to exit maintenance mode.
     start-sleep -s 45
     }
    
     write-host "Enabling host in vCloud Director"
     Enable-CIHost -CIHost $server
     }
     elseif ($state -eq "disable"){
     write-host "Disabling host in vCloud Director"
     Disable-CIHost -CIHost $server
    
     # sleep for 5 seconds for the host to disable in vCD
     start-sleep -s 5
    
     write-host "$server entering maintenance mode"
     $returnCode = set-VMhost -VMHost $server -State Maintenance -Evacuate
     }
    

    PowerCLI: Get HP DL server Serial Number via vCenter and iLO

    February 17th, 2012

    Need a quick and easy way to get the serial numbers from you ESXi servers running on HP hardware?

    Fire up this code (snagged and modified from a vmware community post by RvdNieuwendijk.

    Prerequisites:

    • You have an iLO configured on each server, and online
    • You have vCenter access
    # change the variable to whatever you name your iLO
    # example: -iLO or -OA etc
    $ilo="-ilo"
    get-vmhost | where-object {_.Manufacturer -eq "HP" } | \
    sort-object -Property Name | %{
    
     # Since your ESXi box is attached to vCenter by FQDN,
     # we split the string on "." and take the first
     # element [0] which is the server's short name
     $shortname = ($_.name.split(".")[0])
    
     $xml = new-object system.xml.xmldocument
     # add together $shortname and $ilo to get "server-ilo"
     $xml.load("https://$shortname$ilo/xmldata?item=ALL")
    
     new-object psobject -property @{
       "Name" = $shortname
       # Parse the XML and only grab the server serial number
       "SN" = $xml.RIMP.HSI.SBSN
       }
    }
    
    

    PowerCLI – Generate Count of Running VM’s

    September 8th, 2010

    If you are like me, you have virtual machines in different states in your virtual environment.  Running, paused, or powered-off.  If you have ever been asked “How many VM’s do we have,” and you know the right answer is technically not what vCenter lists as total VM’s, run the following PowerCLI script:

    $vcounter=0
    
    (get-vm )| %{
      $vm = $_
      if( get-vmguest -VM $vm.Name |where-object {$vm.State -eq &quot;Running&quot;}){
        $vcounter++
        }
      }
    
    echo $vcounter
    
    

    Let’s break down line 5, where all of the magic happens.  We are running get-vmguest on the current VM pulled from get-vm on line 3, and then determine if it’s state is “Running.”  PowerCLI and vCenter differ in how they display the state of a VM: “Running” or “Not-Running” in PowerCLI vs “Powered On” or “Powered Off” in vCenter.

    Voila, you now have the count of virtual machines that are Powered-On and theoretically doing work.


    PowerCLI – Gather Virtual Machine Network Information

    August 24th, 2010

    Mapping the virtual networking can be troublesome at times.  How often are you asked to provide MAC addresses to determine what switch port a Virtual Machine is using?  This quick PowerCLI script will walk through and display the VM name, Port Group(s), IP(s) and MAC Address.

    (get-vm) | %{
      $vm = $_
      echo $vm.name----
      $vm.Guest.Nics | %{
        $vminfo = $_
        echo $vminfo.NetworkName $vminfo.IPAddress $vminfo.MacAddress
    
      }
    }
    

    In this example, %{ } will conduct a foreach on each virtual machine from get-vm, and then a foreach on each virtual network adapter assigned to the VM.


    PowerCLI – Physical and Virtual CPU statistics

    June 29th, 2010

    I was recently tasked with providing information regarding CPU averages across our production environment, both physical and virtual.  I know there are other PowerCLI scripts floating around, but it was a good way for me to learn more PowerShell.

    Measure-object and getting the average to show two digits was one of the harder problems to solve (along with get-vmhost $_.NumCPU not working correctly with the version of PowerCLI I had installed).  Lines 29, 31, 49 and 51 are highlighted to show the snip-its.

    It will grab the CPU stats between the days you specify (lines 13,14) from your Virtual Center server, at line 10.  It will spit out a count of your physical hosts, CPUs, Virtual Machines and vCPUs.

    
    # Add in the VI Toolkit goodness
    if ( (Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null )
    {
     Add-PSsnapin VMware.VimAutomation.Core
    }
    
    # Connect to the vCenter server(s)
    $vcserver= @()
    
    $vcserver += connect-VIServer &quot;_Your VC Server_&quot;
    
    # define our start and finish days
    $startdate=(get-date).adddays(-7)
    $finishdate=(get-date).adddays(-1)
    
    # define our silly little counters
    $pCounter = 0
    $vCounter = 0
    $pCPU=0
    $vCPU=0
    
     # print stat dates
     write-host `n --- Statistics for $startdate through $finishdate --- `n
    
     # ---- grab stats for Physical ----
     foreach ($esx_server in (get-vmhost))
     {
     # grab the cpu.usage.average, days are configurable
     $pStats = (get-stat -entity $esx_server -stat cpu.usage.average -Start $startdate -Finish $finishdate | measure-object -property value -average)
     # we only want two decimal places
     $pAvg = [system.math]::round($pStats.average,2)
    
     write-host Physical: $esx_server.name CPU-Average: $pAvg
    
     # increment physical counter
     $pCounter++
    
     # add up the total number of pCPU in cluster
     $pCPU += $esx_server.NumCPU
     }
    
     write-host `nPhysical Host Count: $pCounter
     write-host Physical CPUs: $pCPU `n
    
     # ---- grab stats for Virtual ----
     foreach ($vm_server in (get-vm))
     {
     #grab the cpu.usage.average, days are configurable
     $vStats = (get-stat -entity $vm_server -stat cpu.usage.average -Start $startdate -Finish $finishdate | measure-object -property value -average)
     # we only want two decimal places
     $vAvg = [system.math]::round($vStats.average,2)
    
     write-host Virtual: $vm_server.name CPU-Average: $vAvg
    
     # increment virtual cointer
     $vCounter++
    
     # add up total number of vCPU in cluster
     $vCPU += $vm_server.NumCPU
     }
    
     write-host `nVirtual Host Count: $vCounter
     write-host Virtual CPUs: $vCPU `n
    
    # Disconnect from the vCenter server(s)
    disconnect-viserver $vcserver -Confirm:$False
    
    # END
    ###
    
    

    PowerCLI – Get VMware-Tools versions

    June 22nd, 2010

    Imagine this:

    You are sitting in your cube on a Tuesday morning and your boss walks in and says: “I need all of the installed versions of VMware-Tools to report for compliance!”  Your initially reaction is probably: “really?”  And then you say, OK, I can do that.

    And here is how to do it:

    
    # Add in the VI Toolkit goodness
    if ( (Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null )
    {
    Add-PSsnapin VMware.VimAutomation.Core
    }
    
    # Connect to the vCenter server(s)
    $vcserver= @()
    
    $vcserver += connect-VIServer &quot;&lt;Your vCenter Server&gt;&quot;
    
    # get the vmware tools version for each VM
    
    get-vm |% { get-view $_.id } | select Name, @{ Name=&quot;ToolsVersion&quot;; Expression={$_.config.tools.toolsVersion}}
    
    # Disconnect from the vCenter server(s)
    disconnect-viserver $vcserver -Confirm:$False
    
    # END
    ###
    
    

     

    Your output will be of the form:

    server1.example.com   200000

    server2.example.com   0

    etc.

    Update (3/25/2011): My colleagues found a post on the VMTN page that has to do with my script.  LucD had another idea on how to run the script that would generate so much load on vCenter.  Check it out here.


    PowerCLI Part I

    June 21st, 2010

    Microsoft did a great job with PowerShell.  I take it as 1 part BASH, 2 parts PERL, and probably a few dashes of VB (which I know no dashes).

    VMware blended up their own cmdlets for system automation and reporting.  The useage for the most part is straight-forward, but I have found a few oddities.

    For a few months, I was getting all kids of requests for information from the Management.  Off the top of my head, I can think of:

    • VMware-tools versions installed across the board
    • VM counts across clusters
    • Show VM to LUN mappings

    I leaned heavily on posts by LucD, Virtu-Al, and others, so I’ll post some things I came up with.

    Part I

    I always load in the VI Toolkit PSSnapin at the beginning of every PS1, like so:

    # Add in the VI Toolkit goodness
    if ( (Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null )
    {
    Add-PSsnapin VMware.VimAutomation.Core
    }