Chapter 20
vCloud Air

In this chapter, you will learn to:

  • Prerequisites
  • General
  • vCloud Air Authentication
  • Connecting to vCloud Air
  • Connecting to a Target Datacenter
  • Disconnecting from a Target Datacenter
  • Disconnecting from vCloud Air
  • Set-PowerCLIConfiguration
  • DefaultVIServerMode
  • Scope
  • VMConsoleWindowBrowser
  • WebOperationTimeoutSeconds
  • Open-VMConsoleWindow
  • Tasks
  • Get-CIView
  • ExtensionData
  • API Tasks

vCloud Air is VMware’s solution for a public cloud that is compatible with your on-premises vSphere environment. vCloud Air allows users to migrate workloads to the cloud without changing the format of your virtual workloads, allowing for ease of management. vCloud Air can also be managed from the vSphere Web Client, allowing you to manage both on-premises and public clouds in a single pane.

This chapter builds on Chapter 19, “vCloud Director,” as vCloud Air is a somewhat modified version of vCloud Director. The majority of cmdlets and abilities demonstrated in the previous chapter are also applicable to vCloud Air. In this chapter, we will look at methods of authenticating with vCloud Air and selecting your virtual datacenter (vDC). We will also cover ways to troubleshoot issues and how to leverage the underlying API to access additional data and actions for objects within vCloud Air via PowerCLI.

Prerequisites

To be able to perform the tasks and actions in this chapter, you will need to be running PowerCLI 6.0 R1 or higher; this is the version that first introduces vCloud Air–specific cmdlets. You will also need access to a vCloud Air account.

General

While PowerCLI has been maturing for years and great features and functionalities have been released in earlier versions, PowerCLI 6.0 R1 is the first CLI version to bridge the gap between on-premises and vCloud Air environments. This allows administrators the ease of working in both environments with the same CLI. You even gain the ability to work in both on-premises and vCloud Air environments from the same PowerCLI session.

vCloud Air Authentication

Interacting with vCloud Air via PowerCLI is quite simple; it takes only a few seconds to connect. To manage and administer in your public infrastructure, you first need to securely authenticate with the vCloud Air authentication system. Then you can choose a vDC from options based on your entitlements within that environment.

Connecting to vCloud Air

Connecting to vCloud Air became a very simple task with the release of PowerCLI 6.0 R1. PowerCLI 6.0 R1 introduced cmdlets that allow you to connect and disconnect from vCloud Air: Connect-PIserver and Disconnect-PIServer.

The cmdlets allow you to log into your vCloud Air account without having to specify a vCloud Director API URL or vCloud Org based on your entitlements in those environments. Connect-PIserver requires only your username and password. There are three ways you can connect to vCloud Air with this cmdlet. The first is hard-coding your username and password in the command. This approach is not recommended for scripts, but if you are logging into vCloud Air manually, you would type it out like this:

Connect-PIServer -User [email protected] -Password VMware1!

The second method uses the -Credential parameter along with the Get-Credential cmdlet to prompt for the username and password upon execution:

Connect-PIServer -Credential (Get-Credential)

The third method leverages the Credential Store. Beginning with PowerCLI 4.1, VMware included what is known as the Credential Store, which is then populated with VICredentialStoreItems. These items are credentials, which are encrypted and placed in the ${env:\%APPDATA%}VMwarecredstorevicredentials.xml file on your local machine. Using the Credential Store, you can input your username and password for a given host once, which then can be used in the future to connect to hosts with much less effort:

New-VICredentialStoreItem -Host vchs.vmware.com -User [email protected] `
-Password VMware1!

This Credential Store code sets the username and password for the host, vchs.vmware.com, so that any future attempts to log into vCloud Air using the Connect-PIServer cmdlet will not require credentials. You can also store your vCloud Air credentials in the Credential Store using the Connect-PIServer cmdlet and by adding the -SaveCredentials parameter, which will eliminate the need to run the New-VICredentialStoreItem command.

Connecting to a Target Datacenter

Once you have successfully authenticated with the vCloud Air systems, you will need to specify which datacenter you wish to interact with. Here the Get-PIDatacenter and Connect-PIDatacenter cmdlets are used. To retrieve a listing of all your vDCs you are entitled to (found in the web browser under Subscriptions ⇒ Virtual Data Centers) you would simply type

Get-PIDatacenter

In this example, 11 vDCs are available for connection:

Get-PIDatacenter

Name
----
Tech-Preview
PoC-Demo
UAT-Demo
Personal-Lab
Benchmarks
SDDC-Demo
4-29
M589572327-4001
M673551135-4963
M588570327-5450
M662788264-4629

Once your list returns, you can connect to the target datacenter. For this example, we will choose SDDC-Demo:

$DcConnection = Get-PIDatacenter SDDC-Demo | Connect-PIDatacenter

If you look at what is stored in the $DcConnection variable you get:

$DcConnection

Name                           User                           Org
----                           ----                           ---
p1v22-vcd.vchs.vmware.com      [email protected]          SDDC-Demo

Now that you have connected to your vDC and your connection information is stored in the $DcConnection variable, you can use values from the extended properties within your scripts. You can also use them as you troubleshoot issues, should any arise. Further information can be listed about your connection, such as connection status, SessionId, connection port, and more, if you use the Format-List cmdlet.

Disconnecting from a Target Datacenter

Disconnecting from the target datacenter is very simple. Just like disconnecting from vCloud Director or from hosts in your on-premises environment, you use the Disconnect verb—in this case, Disconnect-PIDatacenter. There is currently no way to specify which vDC to disconnect from, so this command will disconnect each vDC session that you have open:

Disconnect-PIDatacenter -Confirm:$false

Running this command disconnects you from your vDC(s) but keeps you authenticated against vCloud Air and allows you to connect to other vDCs within the same vCloud Air account.

Disconnecting from vCloud Air

It is always best practice to close your connection when you finish running scripts or are finished with your current session. If you are connected to only one server, you can run Disconnect-PIServer -Confirm:$false. While the Disconnect-PIServer accepts the server name, wildcard (*), or connection object, it is wise to decide on a method you and others agree on and use the chosen method for consistency. If you saved your connection as a variable at the beginning of your PowerCLI session, you can reference the same connection variable to disconnect:

$Connection = $global:DefaultPIServers
Disconnect-PIServer $Connection -Confirm:$false

Set-PowerCLIConfiguration

Not often do users need to adjust the PowerCLI configuration settings. In fact, many users forget the Set-PowerCLIConfiguration cmdlet even exists. However, there are a number of settings here that can help you as you leverage PowerCLI for connections to vCloud Air.

DefaultVIServerMode

As you begin working with multiple connections throughout your vSphere infrastructure, you will likely receive a warning that you are connecting to more than one server at a time (depending on what your PowerCLIConfiguration settings are). This does not happen with vCloud Air accounts, but there may be times when you do not remember which account you are using to connect to vCloud Air. You can retrieve the values stored in the $Global:DefaultPIServers variable, which will return the vCloud Air usernames that you are currently connected with:

$global:DefaultPIServers

Name                           User
----                           ----
vchs.vmware.com                [email protected]

Scope

Scope is a parameter that must be used in addition to another settings change to be beneficial. It can be a valuable parameter to set when working with the Set-PowerCLIConfiguration cmdlet. Scope allows you to define the magnitude of the settings you are changing. The values you can choose are Session, User, or AllUsers.

  1. Session Session is the most restrictive with the smallest magnitude. Any setting changed while Scope is set to Session will revert once the PowerCLI console is closed.
  2. User User allows the user’s settings to stay persistent as long as the PowerCLI session can detect the user. This is handy when you are sharing a machine with other individuals who may want to set up their environment and configuration their own way. Your changes will stay in effect even after closing your PowerCLI session.
  3. AllUsers The final option is the AllUsers scope, which, as it is plainly defined, will set all configuration changes for all users of PowerCLI on that computer.
    Set-PowerCLIConfiguration -Scope User -DefaultVIServerMode Single

This example command sets my PowerCLI sessions to only store the most recent VIServer connection. This may be beneficial if you are troubleshooting or attempting to perform a task where you want to ensure that all commands are hitting the target infrastructure and only values from that target infrastructure are returned.

VMConsoleWindowBrowser

This parameter is especially important if you use PowerCLI to open the virtual machine console window directly rather than through the thick client or the web client. VMConsoleWindowBrowser allows you to choose which browser will be used when opening your virtual machine console. If, for example, your default web browser is Internet Explorer, but you decide you want to use Google Chrome for consoling your virtual machines, you can specify Chrome here:

Set-PowerCLIConfiguration -Scope User -VMConsoleWindowBrowser `
"C:Program Files (x86)GoogleChromeApplicationchrome.exe" `
-Confirm:$false

Now, since that you have committed the change to the User scope, the VM Console window will open in Google Chrome for you, even after closing the PowerCLI session, giving you the benefits of using the browser you chose.

WebOperationTimeoutSeconds

Normally there isn’t a need to change the default setting (5 minutes) of WebOperationTimeoutSeconds. This is the length of time the PowerCLI session will attempt to perform web operations before timing out. It is useful to know that this parameter exists, especially if you do not have a solid Internet connection, in which case it may benefit you to increase the timeout value:

Set-PowerCLIConfiguration -Scope AllUsers -WebOperationTimeoutSeconds 500

Open-VMConsoleWindow

As mentioned previously, in setting the default web browser for the VM Console Window you can open the console window for any virtual machine. This allows you to console any virtual machine in your environment (especially vCloud Air) without having to authenticate through your web browser first. This is a very easy way to control a machine quickly and seamlessly.

If you need to work with or troubleshoot a vApp, a simple way to console each machine is to run the following command:

Get-PIVApp Nested | Get-PIVM | Open-VMConsoleWindow

This in turn opens a console tab for every virtual machine in the given vApp. Additionally, you can add the -Fullscreen parameter to launch the console window in full-screen mode. Tabs still open in your web browser, but they run a full-screen window.

Tasks

Understanding what is going on in your vCloud Air is crucial both for troubleshooting issues and for the day-to-day operations taking place in your cloud. PowerCLI provides the Get-Task cmdlet so you can retrieve tasks that have been performed in your vCloud Air instance. Get-Task in vCloud Air operates in a manner similar to the way Get-Task works in vSphere.

When you run the Get-Task cmdlet, generally numerous tasks are returned. This makes sorting through them somewhat difficult, especially if you are trying to troubleshoot an issue. You can filter through the returned tasks several ways. The first is by filtering on a given property, such as the task state, which can be especially useful when troubleshooting:

Get-Task | where {$_.State -eq "Error"}

This will return any failed task and will (hopefully) return a much smaller more relevant subset of tasks. You can also search by properties such as Cancelled, Cancelable, Result, QueueTime, StartTime, CompleteTime, Name, PercentComplete, and more. Employing these and other properties will narrow down the task results significantly.

One of the most common filters used with these tasks is Start Time. You can specify how far back in time you want to retrieve results. The only problem with returning results off time/date-based properties is the syntax used. For example, if you want to retrieve all results in the past two days, you would enter something like this:

Get-Task | where `
    {$_.StartTime -gt (Get-Date).AddDays(-2)} `
    | select Name, State, StartTime

As you can see, it’s not as simple as just typing in a time to go back to—it requires you to subtract time from the current time (Get-Date). The format for TimeSpan is 'Days.Hours:Minutes:Seconds'. Listing 20-1 is a simple function that takes care of the formatting for you and allows you to specify time using -Days, -Hours, and -Minutes parameters. This function does not allow for seconds.

Once the results have been retrieved, you can then work through the results to find the desired information, such as if a task was successful or not and what the action was. Here’s an example:

$erroredtasks = Filter-Tasks -Days 7
$erroredtasks | where {$_.state -eq "error"}

Listing 20-1: Filtering vCloud Air tasks

function Filter-Tasks {
<#
.SYNOPSIS
 Easy Task filtering function for vCloud Air
.DESCRIPTION
 This function allows you to easily filter tasks
 by Days/Hours/Minutes to sort through actions
 within vCloud Air
.NOTES
  Source:  Automating vSphere Administration
.PARAMETER Days
 Parameter to select number of days back to filter
.PARAMETER Hours
 Parameter to select number of hours back to filter
.PARAMETER Minutes
 Parameter to select number of minutes back to filter
.EXAMPLE
 Filter-Tasks -Days 3 -Hours 6 -Minutes 20
 $Tasks | fl *
.EXAMPLE
 Filter-Tasks -Hours 12
 $Tasks | Select Name, State, StartTime
  
#>
  Param(
  [int]$Days = 0,
  [int]$Hours = 0,
  [int]$Minutes = 0
  )

  process{
  $ts = New-TimeSpan -Hours $Hours -Minutes $Minutes -Days $Days
   Get-Task | Where-Object {$_.StartTime -gt ((Get-Date) - $ts)}
  }
}

Get-CIView

Just as PowerCLI has the Get-View cmdlet for vSphere, which allows administrators to return vSphere View objects and to work with the underlying vSphere API, the Get-CIView cmdlet fulfills the same function for vCloud Director as well as vCloud Air. Get-CIView is a very powerful way to not only retrieve more detailed information about the target object, but also to perform tasks via the API.

ExtensionData

ExtensionData is a property that exposes information for a given object via the API. It allows users to dig down deep into a given object. The information returned by the ExtensionData property can be used for reporting, for troubleshooting, or even for invoking API tasks. Let’s see what is returned when looking at both a specific vApp and its virtual machines.

In this example, we have created a variable, $vApp, which is populated with the returned CIView object:

$vApp = Get-PIVApp Nested | Get-CIView
$vApp


OvfDescriptorUploaded : True
Owner                 : VMware.VimAutomation.Cloud.Views.Owner
InMaintenanceMode     : False
Children              : VMware.VimAutomation.Cloud.Views.VAppChildren
Deployed              : True
VAppParent            :
Section               : {VMware.VimAutomation.Cloud.Views.LeaseSettingsSection,
                         VMware.VimAutomation.Cloud.Views.OvfStartupSection,
                        VMware.VimAutomation.Cloud.Views.OvfNetworkSection,
                        VMware.VimAutomation.Cloud.Views.NetworkConfigSection}
DateCreated           : 3/17/2015 4:01:07 PM
Status                : 10
Files                 :
Name                  : Nested
Description           :
Tasks                 :
Id                    : urn:vcloud:vapp:c943b4dc-b66f-4671-822a-e414edcec213
OperationKey          :
Client                : VMware.VimAutomation.Cloud.Views.CloudClient
Href                  : https://p5v43-vcd.vchs.vmware.com:443/api/vApp/vapp-c94
                        3b4dc-b66f-4671-822a-e414edcec213
Type                  : application/vnd.vmware.vcloud.vApp+xml
Link                  : {, , , ...}
AnyAttr               : {xsi:schemaLocation}
VCloudExtension       :

As you can see, there are a number or properties that can be useful when generating reports, troubleshooting, or just navigating the additional information of the vApp. The properties with values starting with VMware. can be navigated even deeper by adding the property name to the end of the vApp variable we created:

$vApp.children

VApp                Vm                  AnyAttr             VCloudExtension
----                --                  -------             ---------------
                    {ESXi7, ESXi8, M...

There are multiple virtual machines within this vApp. You can see the list of virtual machines and their properties by going yet another level deeper by adding vm to the end of the vApp variable:

$vApp.children.Vm


NeedsCustomization      : True
NestedHypervisorEnabled : False
VAppScopedLocalId       : e1bca7ba-50b2-45b1-b8d0-f7c935e9cd1c
Environment             :
VmCapabilities          : VMware.VimAutomation.Cloud.Views.VmCapabilities
StorageProfile          : VMware.VimAutomation.Cloud.Views.Reference
Deployed                : False
VAppParent              :
Section                 : {, 101, VMware.VimAutomation.Cloud.Views.NetworkConne
                          ctionSection, ...}
DateCreated             :
Status                  : 8
Files                   :
Name                    : ESXi7
Description             :
Tasks                   :
Id                      : urn:vcloud:vm:8862e80d-a6bf-426e-9287-057e037d40dd
OperationKey            :
Client                  : VMware.VimAutomation.Cloud.Views.CloudClient
Href                    : https://p5v43-vcd.vchs.vmware.com:443/api/vApp/vm-886
                          2e80d-a6bf-426e-9287-057e037d40dd
Type                    : application/vnd.vmware.vcloud.vm+xml
Link                    : {, , , ...}
AnyAttr                 :
VCloudExtension         :

NeedsCustomization      : True
NestedHypervisorEnabled : False
VAppScopedLocalId       : 9d7790a2-e6b3-4e59-b528-352d5650304d
Environment             :
VmCapabilities          : VMware.VimAutomation.Cloud.Views.VmCapabilities
StorageProfile          : VMware.VimAutomation.Cloud.Views.Reference
Deployed                : False
VAppParent              :
Section                 : {, 101, VMware.VimAutomation.Cloud.Views.NetworkConne
                          ctionSection, ...}
DateCreated             :
Status                  : 8
Files                   :
Name                    : ESXi8
Description             :
Tasks                   :
Id                      : urn:vcloud:vm:61716aba-4022-4f4b-86f2-c73c00f056a11f
OperationKey            :
Client                  : VMware.VimAutomation.Cloud.Views.CloudClient
Href                    : https://p5v43-vcd.vchs.vmware.com:443/api/vApp/vm-617
                          16aba-4022-4f4b-86f2-c73c00f056a11f
Type                    : application/vnd.vmware.vcloud.vm+xml
Link                    : {, , , ...}
AnyAttr                 :
VCloudExtension         :

You can continue to navigate through the extension data of this variable to retrieve the desired information. This is very helpful for reporting on your environment and finding data about objects in your environment quickly.

Listing 20-2 is a function that can be used to generate reports on your vCloud Air environments. This function leverages the extension data of each vApp and virtual machine object in your vDC. The function is easily run with only a single parameter (-Filename) that specifies the destination location for the HTML report:

Get-PIReport -Filename C:TempvCloudAirReport.HTML

Listing 20-2: Generating vCloud Air reports

function Get-PIReport {
<#
.SYNOPSIS
 Returns HTML report of your vCloud Air Environment
.DESCRIPTION
 This report lists the vApps and VMs along with their settings
.NOTES
  Source:  Automating vSphere Administration
.PARAMETER Filename
 This parameter sets the destination location of the report
.EXAMPLE
 Get-PIReport -Filename C:TempPIReport.html
  
#>

  Param(
  [Parameter(Mandatory = $True, Position = 1)]
  [String]$Filename
  )

  process{
  
# Create arrays to be used
$objects = @()
$VMs = @()

# Cycle through all vApps and populate report objects
foreach ($vApp in (Get-PIVApp)) {
 $CurrentvApp = Get-PIVApp $vApp | Get-CIView
$Object = New-Object -TypeName PSObject -Property ([ordered]@{
 Name = $CurrentvApp.Name
 CreationDate = $CurrentvApp.DateCreated
 Owner = $CurrentvApp.Owner.User.name
 Description = $CurrentvApp.Description
 Deployed = $CurrentvApp.Deployed
 DeploymentLeaseinSeconds = `
 $CurrentvApp.Section.DeploymentLeaseinSeconds
 StorageLeaseInSeconds = `
 $CurrentvApp.Section.StorageLeaseInSeconds
 DeploymentLeaseExpiration = `
 $CurrentvApp.Section.DeploymentLeaseExpiration
 StorageLeaseExpiration = `
 $CurrentvApp.Section.StorageLeaseExpiration
 Networks = [string]::Join("`r`n", `
 $CurrentvApp.Section.Network.Name)
}) 

$objects += $Object
 # Populate the VMs array with the children VMs of each object
 foreach ($VM in ($CurrentvApp.Children.VM | Sort-Object Name))`
 {
 $VMObject = New-Object -TypeName PSObject -Property ([ordered]@{
 vApp = $vApp.Name
 Name = $VM.Name
 Description = $VM.Description
 Deployed = $VM.Deployed
 NeedsCustomization = $VM.NeedsCustomization
 NestedHypervisorEnabled = $VM.NestedHypervisorEnabled
 MemoryHotAdd = $VmCapabilities.MemoryHotAddEnabled
 CPUHotAdd = $VM.VmCapabilities.CpuHotAddEnabled
 StorageProfile = $VM.StorageProfile.Name
 VMID = $VM.Section.VirtualMachineID
 ComputerName = $VM.Section.ComputerName
 DomainName = $VM.Section.DomainName
})

   
 $VMs += $VMObject }
 
}
# Add HTML CSS
$Header = @"
<style>
TABLE {border-width: 2px;border-style: solid;`
border-color: black;border-collapse: collapse;}
TH {border-width: 2px;padding: 3px;`
border-style: solid;border-color: black;background-color: #6495EF;}
TD {border-width: 2px;padding: 3px;`
border-style: solid;border-color: black;}
TR:Nth-Child(Even) {Background-Color: #dddddd;}
</style>
"@
 
# Add Titles for each section
$Pre = "<H1>vApp Overview</H1>"
$Post = "<br><br><br>VM Overview"

# Combine all pieces of the report
$VMReport = "<H1>VM Overview</H1>"
$VMReport += $VMs | ConvertTo-Html -Head $Header 

# Export report to destination filepath
$Objects | ConvertTo-HTML -Head $Header -PreContent $Pre `
-PostContent $VMReport | Out-File $Filename -Force

  }
}

API Tasks

Not only can the Get-CIView cmdlet retrieve information about objects in your environment, but it can be used to invoke tasks on those objects using the methods that are available. Each object can be piped to Get-Member (or gm for short) to retrieve a list of actions (also known as methods) you can take on the specified object.

To achieve this, you will need to specify the CIView of an object. In this example, we’ll select the Jumpbox virtual machine from within the “nested” vApp referred to in the “Extension Data” section of this chapter.

$vm = Get-PIVM Jumpbox | Get-CIView

You can then retrieve the methods in one of two ways. The first retrieves all member types of the object, whereas the second filters the results to show only the methods:

$vm | Get-Member 

or

$vm | Get-Member -MemberType Method
   TypeName: VMware.VimAutomation.Cloud.Views.Vm

Name                         MemberType Definition
----                         ---------- ----------
AcquireMksTicket             Method     VMware.VimAutomation.Cloud.Views.Mks...
AcquireTicket                Method     VMware.VimAutomation.Cloud.Views.Scr...
Attach                       Method     void Attach(System.Nullable[int] bus...
Attach_Task                  Method     VMware.VimAutomation.Cloud.Views.Tas...
CheckCompliance              Method     void CheckCompliance()
CheckCompliance_Task         Method     VMware.VimAutomation.Cloud.Views.Tas...
Consolidate                  Method     void Consolidate()
Consolidate_Task             Method     VMware.VimAutomation.Cloud.Views.Tas...
ControlAccess                Method     VMware.VimAutomation.Cloud.Views.Con...
CreateMetadata               Method     void CreateMetadata(VMware.VimAutoma...
CreateMetadata_Task          Method     VMware.VimAutomation.Cloud.Views.Tas...
CreateSnapshot               Method     void CreateSnapshot(System.Nullable[...
CreateSnapshot_Task          Method     VMware.VimAutomation.Cloud.Views.Tas...
CustomizeAtNextPowerOn       Method     void CustomizeAtNextPowerOn()
Delete                       Method     void Delete()
Delete_Task                  Method     VMware.VimAutomation.Cloud.Views.Tas...
Deploy                       Method     void Deploy(System.Nullable[bool] po...
Deploy_Task                  Method     VMware.VimAutomation.Cloud.Views.Tas...
Detach                       Method     void Detach(System.Nullable[int] bus...
Detach_Task                  Method     VMware.VimAutomation.Cloud.Views.Tas...
…

Let’s say that you wanted to create a snapshot of this virtual machine. No cmdlet is available that can do this for you, but you do have the CreateSnapshot method. To see the information required to run the CreateSnapshot method, add the method name to the end of your variable:

$vm.CreateSnapshot

OverloadDefinitions
-------------------
void CreateSnapshot(System.Nullable[bool] memory, System.Nullable[bool]
quiesce, string name, string description)

In the OverloadDefinitions property you can see how the method needs to be formed. For all intents and purposes, to make this work you only need a name for the snapshot; the description is optional, but if you do not add a description, you should use $null as a placeholder. To create the virtual machine snapshot, your command would look like this:

$vm.CreateSnapshot($null,$null,"Snapshot Name",$null)

As you dive deeper into the Get-Member methods of objects in vCloud Air, you open the door to do great things—as well as potentially do great harm. It is important that you understand what each method will do before invoking it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset