Chapter 19
vCloud Director

In this chapter, you will learn to:

  • Prerequisites
  • Connecting to vCloud Director
  • Manage Organizations
  • Creating Organizations
  • Enabling/Disabling Organizations
  • Organization Networks
  • Organization Review Summary
  • Manage Users
  • Access Control Rules
  • Manage vDCs
  • Provider vDCs
  • Organization vDCs
  • Manage vApps
  • Power Commands
  • vApp Configuration
  • vApp Networking
  • vApp Templates
  • Manage VMs
  • Power Commands
  • Start Rules
  • vCloud Director Networks
  • Search-Cloud

vCloud Director allows users to build multitenant private clouds on top of VMware infrastructure by creating virtual datacenters with server resources and providing it to their customers via a web-based portal. Although it is no longer available to new users, there are automation advantages for existing users and service providers.

This chapter takes you through some common tasks that can be automated within vCloud Director. Since vCloud Director is now only sold to service providers, the main focus of this chapter will be administration of the vCloud Director infrastructure. Administration and automation of tenants can be found in Chapter 20, “vCloud Air.” This chapter assumes that you have already deployed the vCloud Director product, that it has been configured at least to the point that the administrator can log into the vCloud Director homepage, and that vCloud Director is attached to a vCenter. From here, you will learn to automate tasks like creating provider virtual datacenters (vDCs), external networks, network pools, and organizations; allocating resources; and managing users.

Prerequisites

To be able to connect to and administer in vCloud Director, you must ensure that the vCloud Air/vCD PowerCLI feature is installed. You select this feature during the installation of PowerCLI, and it provides cmdlets for automating vCloud Air and vCloud Director features. If PowerCLI was installed without the vCloud Air/vCD feature, you can rerun the PowerCLI installer and add this feature to continue (see Figure 19-1).

c19f001.tif

Figure 19-1: New vCloud Air/vCD install feature

Use the code in Listing 19-1 to see a list of commands that can be run in vCloud Director. This will return all the cmdlets available for use within vCloud Director. Notice that a majority of these command names contain the characters CI (for Cloud Infrastructure).

Listing 19-1: Obtaining a list of vCloud Director cmdlets

# Return any module ending in .Cloud and save it to a variable
$mod = Get-Module *.Cloud -ListAvailable

# Use the Get-Command cmdlet searching for the target module and filter on Cmdlet
Get-Command -Module $mod -Type Cmdlet | Select Name, ModuleName

Connecting to vCloud Director

Before you can work within the vCloud Director environment, you must log on to the target private cloud to authorize the PowerCLI session. You then can connect to vCloud Director using the Connect-CIServer command:

Connect-CIServer -Server vCD.vmwarelab.com -User Administrator -Password VMware1!

At times, it is beneficial to run multiple PowerCLI sessions against vCloud Director at the same time. This may be through the use of PowerShell jobs, scripts invoking other scripts, and so on. You can leverage a single vCD logon across multiple sessions by grabbing the SessionSecret from your main PowerCLI session when logging into vCloud Director:

$connection = Connect-CIServer -Server vCD.vmwarelab.com -User Administrator `
-Password VMware1!

You can also run this command without placing your credentials in your code by using the Get-Credential cmdlet:

$connection = Connect-CIServer -Server vCD.vmwarelab.com -Credential `
(Get-Credential)

When prompted, enter your username and password without revealing it within your script. Once you’ve used that line of code to connect to vCloud Director, you can see your SessionSecret:

$connection.SessionSecret
526da858-9d41-2760-7d90-4d30fc4635aa

You can then use the SessionSecret to log into vCloud Director in your other PowerCLI sessions by using the -SessionID parameter:

Connect-CIServer -Server vCD.vmwarelab.com -SessionID $connection.SessionSecret

This allows you to log on to other sessions without entering a username and password as long as the main connection stays active.

Manage Organizations

vCloud Director Organizations (also known as orgs) are the topmost containers whereon the rest of the private cloud is created. Within these organizations, administrators can create org vDCs (virtual datacenters), add local users, create vApps, manage catalog items, and allocate virtual resources. Service providers may find it necessary to create new orgs from time to time, as well as disable or remove orgs. This section will cover the administration and management of orgs.

Creating Organizations

Organizations are one of the objects that can be created using PowerCLI. The cmdlet New-Org requires two parameters: Name and FullName.

New-Org -Name Customer1 -FullName Customer_X_Seattle `
-Description "This is Customer X in Seattle"

Org names and descriptions can easily be updated using the Set-Org cmdlet as well:

Get-Org -Name Customer1 | Set-Org -FullName Customer_Y_Orlando `
-Description "This customer is based out of Orlando"

Enabling/Disabling Organizations

Once a new org is created, it is enabled by default. Generally this is fine, but sometimes administrators need to disable an organization. When this happens, it is easy to use PowerCLI to disable the target organizations:

Get-Org -Name Customer1 | Set-Org -Enabled:$false

When an org is disabled, it cannot deploy or power on any additional vApps until it has been re-enabled. An org must be disabled before it can be removed.

Organization Networks

Each org requires its own org vDC network. More org vDC networks can be associated to each org. These networks fulfill different purposes within the org. There are three network types that can be used within the org:

  1. Internal An internal connection is a completely isolated network for all machines within the org vDC. No network traffic can traverse the org vDC boundary to any other organization’s network or an external network.
  2. Direct A direct connection is just what it sounds like. It provides layer 2 network access outside of the org vDC. This type of connection does not need an edge gateway.
  3. Routed A routed connection allows network access outside of the org vDC. Routed connections also allow for vApps and virtual machines to be accessed from an external network. To use this type of connection, you must provision an edge gateway. Additional security measures and configuration can take place on the edge gateway to ensure that only the network traffic you desire can pass through in or out of the routed connection.

You will most likely encounter each type of network throughout various org vDCs in your environment. You can use the following code to report on the networks that currently exist:

Get-OrgNetwork | Select Name, NetworkType, Gateway, `
PrimaryDns, SecondaryDns, Netmask

Organization Review Summary

You may be asked from time to time to review the organizations in your environment. From a purely mathematical and operations point of view, simply running the Get-Org cmdlet and filtering out unwanted information to leave you with the name of the org, settings, and statistics will return the necessary information:

Get-Org | Select Name, FullName,Description, Enabled, `
CanPublish,DeployedVMQuota, StoredVMQuota, VdcCount, `
CatalogCount, VAppCount | Export-Csv `
-Path C:TempOrgSummary.CSV -NoTypeInformation -NoClobber

Manage Users

vCloud Director cmdlets do not allow for adding or modifying users, but they are available for reporting and auditing. These cmdlets allow administrators to quickly and easily create these reports to validate the settings, roles, and properties of users in each org. The Get-CIUser and Get-CIRole cmdlets can be used together for more in-depth views of the users configuration.

Get-Org | Foreach { `
Write-Host " Org: $($_.Name) " -ForegroundColor Green; `
Get-CIUser -Org $_ | Foreach { `
Write-Host $_.Name -ForegroundColor yellow; `
Get-CIRole -user $_.Name}}

Access Control Rules

It is critical to create rules and roles for objects within your private cloud environment. As in vCenter, you can define roles and rights for different users and groups within vCloud Director. It is wise to review each access control rule periodically. In addition to the roles and rights given to users and groups, you can set access control levels on objects within your vCloud Director environment.

Creating Access Control Rules

To create new access control rules, use the New-CIAccessControlRule cmdlet. This requires several parameters to succeed: -AccessLevel, -User or -EveryoneInOrg, and -Entity. The access level allows you to specify Read, ReadWrite, or FullControl permissions for the selected object. You can choose specific users for a given access level, or you can set it for everyone in the organization of the selected object. Entity refers to the object that will receive the access control rules; this may be either a catalog or a vApp object.

Let’s say that you do not want others to be able to change the configuration of a specific vApp. You could create a new access control rule that gives all users read-only access to that vApp:

New-CIAccessControlRule -Entity 'SecuredVApp' -EveryoneInOrg `
-AccessLevel "Read" -Confirm:$false

Reviewing Access Control Rules

Once you are connected to a vCloud Director server, you can retrieve a listing of all access control rules using a simple Get-CIAccessControlRule cmdlet, which will return all the rules that have been created for the entire vCloud Director environment. (It is wise to review this list periodically.)

Get-CIAcessControlRule

You can specify the scope of this cmdlet and return rules that have been created based on the catalog or vApp object, user, or access level. Use the Sort-Object cmdlet to organize the results:

Get-CIAccessControlRule | Sort-Object AccessLevel | `
Select Entity, AccessLevel, User

Note that if an access level has been set for EveryoneInOrg, the user that is returned is the name of the organization rather than a specific user or a list of all the users included in the organization.

Modifying Access Control Rules

Once access control rules have been created, there may come a time that a specific rule needs to be modified. There are two different ways of changing a rule that has already been created. The best way to do it is to use the Set-CIAccessControlRule cmdlet, which allows you to update the properties of an existing rule. The second way is to use the New-CIAccessControlRule cmdlet and add the -Force parameter, overwriting the settings of the previous rule.

Using the Set-CIAccessControlRule, you can update the settings of a rule as follows:

$rule = Get-CIAccessControlRule -Entity 'SecuredVApp' `
-User OrgVDC
$rule | Set-CIAccessControlRule -AccessLevel "FullControl"

or:

Get-CIAccessControlRule -Entity 'SecuredVApp' 
-User OrgVDC| `
Set-CIAccessControlRule -AccessLevel "FullControl"

Both of these options achieve the same results.

Deleting Access Control Rules

Removing an access control rule is a simple task similar to that of modifying a rule. The one note of caution here is to make sure that you only delete the specific rule intended. To delete a rule, use the Get-CIAccessControlRule cmdlet to specify the entity on which the rule resides:

Get-CIAccessControlRule -Entity 'SecuredVApp'

Once you verify that the command returns only the intended rule(s), you can press the up arrow in your PowerCLI session and pipe the results of the previous command to the Remove-CIAccessControlRule cmdlet:

Get-CIAccessControlRule -Entity 'SecuredVApp'| Remove-CIAccessControlRule

Manage vDCs

There are two types of virtual datacenter constructs within vCloud Director:

  1. Provider Provider vDCs are a pool of compute and memory resources from the underlying virtualization platform that can be offered up and consumed within the private cloud.
  2. Organization Org vDCs are used to allocate resources from the provider vDC for use within the given organization.

Provider vDCs

vCloud Director does not have any native cmdlets for creating a provider vDC. Since the provider vDC must be set up and configured to build the rest of your private cloud, PowerCLI offers a single cmdlet to view the properties of a provider vDC: Get-ProviderVdc. The Get-ProviderVdc cmdlet returns a summary of all the provider vDCs and includes the status, resources used, and whether the vDC is enabled or disabled.

Get-ProviderVdc

More information can be pulled from this cmdlet by piping the results to a formatted list (fl):

Get-ProviderVdc | fl *
Href              : https://vcd-l-01a/api/admin/extension/provid
                    ervdc/a1891824-e45f-43b6-acab-a9492c8aead9
StorageUsedGB     :
StorageOverheadGB :
StorageTotalGB    : 0
StorageAllocatedGB:
Status            : Ready
MemoryUsedGB      : 2.34765625
MemoryOverheadGB  : 0
MemoryTotalGB     : 2.60546875
MemoryAllocatedGB : 0
Enabled           : True
CpuUsedGHz        : 0
CpuOverheadGHz    : 0
CpuTotalGHz       : 7.614
CpuAllocatedGHz   : 0
ExtensionData     : VMware.VimAutomation.Cloud.Views.VMWProvider
                    Vdc
Description       : example pVDC
Id                : urn:vcloud:providervdc:a1891824-e45f-43b6-ac
                    ab-a9492c8aead9
Name              : MainpVDC
Client            : /CIServer=administrator:system@vcd-l-01a:443
Uid               : /CIServer=administrator:system@vcd-l-01a:443
                  /ProviderVdc=urn:vcloud:providervdc:a1891824-e
                  45f-43b6-acab-a9492c8aead9/

As you can see, a bit more data is returned when you use the Format-List cmdlet. You can create a report of provider vDCs that returns key information for the providers in your vCloud Director environment, as shown in Listing 19-2.

Listing 19-2: Provider vDC reporting

function Get-ProviderVdcReport {
<#
.SYNOPSIS
 Report of all Provider vDCs in the environment
.DESCRIPTION
 This function will write a report to CSV with key information
 About each Provider vDC including resource information and
 Other metrics.
.NOTES
  Source:  Automating vSphere Administration
.PARAMETER Path
 Path is the destination and CSV name for where the report
 will be exported to.
.PARAMETER Memory
 Reports Memory metrics on each Provider vDC. Can be used
 with -CPU and -Storage parameters
.PARAMETER CPU
 Reports CPU metrics on each Provider vDC. Can be used
 with -Memory and -Storage parameters
.PARAMETER Storage
 Reports Storage metrics on each Provider vDC. Can be used
 with -Memory and -CPU parameters
.PARAMETER All
 Reports on all three parameters (Memory, CPU, Storage) and
 must be called by itself.
.EXAMPLE
 Get-ProviderVdcReport -Path c:TempProvidervDCReport.csv -All
 Show all metric information for each pVDC
.EXAMPLE
 Get-ProviderVdcReport -Path c:TempProvidervDCReport.csv `
 -Storage -CPU
 Show Storage and CPU metric information for each pVDC

#>
[CmdletBinding(DefaultParameterSetName = "All")]
param (

[Parameter(Mandatory = $True)]
[string]$Path,

# Set parameters into a ParameterSetName for grouping
[Parameter(ParameterSetName = 'Resources')]
[switch]$Memory,
[Parameter(ParameterSetName = 'Resources')]
[switch]$CPU,
[Parameter(ParameterSetName = 'Resources')]
[switch]$Storage,

# Set All in different ParameterSetName to not be used with Resources
[Parameter(ParameterSetName = 'All')]
[switch]$All = $true
)

process {

#Create empty array
$PvDCs = @()
foreach ($PvDC in (Get-ProviderVdc)) {

#Default pVDC information
$pVDCProperties = @{
       Name = $PvDC.Name
       Description = $PvDC.Description
       Enabled = $PvDC.Enabled
       Status = $PvDC.Status
}

#Storage
if (($Storage) -or ($All)) {
       $pVDCProperties$pVDCProperties["StorageUsedGB"] = $PvDC.StorageUsedGB
       $hshPropertiesForNewObj["StorageOverheadGB"] = $PvDC.StorageOverheadGB
       $pVDCProperties["StorageTotalGB"] = $PvDC.StorageTotalGB
       $pVDCProperties["StorageUsedPcnt"] = $(if ($PvDC.StorageTotalGB -gt 0) `
       {($PvDC.StorageUsedGB / $PvDC.StorageTotalGB) * 100})
}

#Memory
if (($Memory) -or ($All)) {
       $pVDCProperties["MemoryUsedGB"] = $PvDC.MemoryUsedGB
       $pVDCProperties["MemoryOverheadGB"] = $PvDC.MemoryOverheadGB
       $pVDCProperties["MemoryTotalGB"] = $PvDC.MemoryTotalGB
       $pVDCProperties["MemoryAllocatedGB"] = $PvDC.MemoryAllocatedGB
       $pVDCProperties["MemoryOverAllocatedPcnt"] = $(if ($PvDC.MemoryTotalGB `
       -gt 0) {($PvDC.MemoryAllocatedGB / $PvDC.MemoryTotalGB) * 100}) 
}

#CPU
if (($CPU) -or ($All)) {
       $pVDCProperties["CPUUsedGHz"] = $PvDC.CpuUsedGHz
       $pVDCProperties["CpuOverheadGHz"] = $PvDC.CpuOverheadGHz
       $pVDCProperties["CpuTotalGHz"] = $PvDC.CpuTotalGhz
       $pVDCProperties["CpuAllocatedGHz"] = $PvDC.CpuAllocatedGHz
       $pVDCProperties["CpuOverAllocatedPcnt"] = ($PvDC.CpuAllocatedGHz / `
       $PvDC.CpuTotalGhz) * 100
}

$vDC = New-Object -TypeName PSObject -Property $pVDCProperties


}
#Set -NoClobber to not overwrite existing files
$PvDCs | Export-Csv "$Path" -NoTypeInformation -NoClobber

#Verify the file was created
if(!(Test-Path $Path)){Write-Warning "It appears that the CSV `
file was not created. Please try again."} else `
{Write-Verbose "File Saved Successfully to '$Path'"}
}

}

Organization vDCs

Within your organization, you can split up the resource allocation and configurations by using org vDCs. Org vDCs are partitioned from the resources of a provider vDC.

You can get a list of org vDCs by using the Get-OrgVdc cmdlet. This cmdlet will return the same type of information that was returned in the previous section with Get-ProviderVdc, only for the org subset:

Get-OrgVdc

You can narrow the results by provider vDC using the -ProviderVdc parameter:

Get-OrgVdc -ProviderVdc MainpVDC

Listing 19-3 shows you how to export a report to CSV on all of your org vDCs along with critical information about CPU, storage, memory, and overall summary.

Listing 19-3: Org vDC report by org

function Get-OrgVdcSummary {
<#
.SYNOPSIS
 Retrieve a summary of all Organization vDCs by Organization
.DESCRIPTION
 Retrieves critical information about each Org vDC in the
 environment
.NOTES
  Source:  Automating vSphere Administration
.PARAMETER Path
 Specify the file path for the CSV output
.EXAMPLE
 Get-OrgVdcSummary -Path C:TempOrgSummary.csv

#>

  param(
  [Parameter(Mandatory=$true)]
  [ValidateNotNull()]
  [String]$Path
  )

  process{
 foreach ($Org in (Get-Org)){
  foreach ($orgVDC in (Get-OrgvDC -Org $Org.Name)) {
  $CurrentOrg = New-Object -TypeName PSObject -Property @{
         Org = $Org.Name
         OrgVDC = $orgVDC.Name
         Description = $orgVDC.Description
         Enabled = $orgVDC.Enabled
         Status = $orgVDC.Status
         ProviderVdc = $orgVDC.ProviderVdc
         AllocationModel = $orgVDC.AllocationModel
         VMMaxCount = $orgVDC.VMMaxCount
         ThinProvisioning = $orgVDC.ThinProvisioning
         FastProvisioning = $orgVDC.FastProvisioning
       # Network Info
         NetworkPool = $orgVDC.NetworkPool
         NetworkMaxCount = $orgVDC.NetworkMaxCount
         NicMaxCount = $orgVDC.NicMaxCount
       # Storage Info
         StorageUsedGB = $orgVDC.StorageUsedGB
         StorageLimitGB = $orgVDC.StorageLimitGB
         StorageAllocationGB = $orgVDC.StorageAllocationGB
         StorageOverheadGB = $orgVDC.StorageOverheadGB
         StorageUsedPcnt = ($orgVDC.StorageUsedGB / `
         $orgVDC.StorageAllocationGB)*100
       # Memory Info
         MemoryGuaranteedPercent = $orgVDC.MemoryGuaranteedPercent
         MemoryUsedGB = $orgVDC.MemoryUsedGB
         MemoryLimitGB = $orgVDC.MemoryLimitGB
         MemoryAllocationGB = $orgVDC.MemoryAllocationGB
         MemoryOverheadGB = $orgVDC.MemoryOverheadGB
         MemoryOverAllocatedPcnt = $(if ($orgVDC.MemoryAllocationGB -gt 0) `
         {($orgVDC.MemoryAllocatedGB / $orgVDC.MemoryAllocationGB)*100})
       # CPU Info
         CPUGuaranteedPercent = $orgVDC.CPUGuaranteedPercent
         VMCpuCoreMHz = $orgVDC.VMCpuCoreMHz
         CPUUsedGhz = $orgVDC.CpuUsedGhz
         CpuLimitGhz = $orgVDC.CpuLimitGhz
         CPuOverheadGhz = $orgVDC.CpuOverheadGhz
         CpuOverAllocatedPcnt = ($orgVDC.CpuUsedGHz / $orgVDC.CpuLimitGhz)*100
  }
  

  $CurrentOrg | Export-CSV $Path -Append -NoClobber `
  -NoTypeInformation
  }
  }
  }
}

Manage vApps

vCloud Director uses a different method of organizing virtualizing workloads. All workloads are deployed as vApps, which are an organizational container for one or more virtual machines, their networking, and any policies associated with the VMs. The vApps can be set to boot the encapsulated virtual machines in a specific order as well as set shares and priorities for those machines.

We can use PowerCLI to either import vApps or create new vApp containers that we can populate with virtual machines afterward. If we create a new vApp, we are essentially only creating the container and will need to populate it with virtual machines. In Listing 19-4, we create a new vApp and then import several virtual machines from the underlying vSphere environment, placing them within the new vApp.

Listing 19-4: Creating vApp containers

# Create vApp Container
$NewVApp = New-CIVApp -Name TestvApp `
-Description "Newly Created vApp" -OrgVdc "OrgVdc1"

# Import each Apache VM into newly created vApp
Get-VM -Name Apache* | Foreach {
Import-CIVApp -VM $_ -VApp $NewVApp.Name
}

The code in Listing 19-4 creates a vApp, TestvApp, and imports three virtual machines from vSphere (see Figure 19-2). Note that if we had added the -NoCopy parameter to the Import-CIVApp command, it would have moved the virtual machines out of vSphere and into vCD, rather than creating a copy.

c19f002.tif

Figure 19-2: Imported VMs with vApp

Power Commands

PowerCLI gives you the ability to start, stop, restart, or suspend the vApps using the Start-CIVApp, Stop-CIVApp, Restart-CIVApp, and Suspend-CIVApp cmdlets, respectively. Running any of these four commands invokes the action specified on every virtual machine found within the vApp container. We recommend that all the virtual machines within the vApps be powered off when using these cmdlets, rather than performing the action against specific virtual machines inside the vApp. This ensures that the vApp will start up or shut down properly using the configuration that it has been given.

The Stop-CIVApp and Restart-CIVApp cmdlets do not perform their actions gracefully. By that, we mean that using those commands is the equivalent to hitting the power button or restart button on your computer chassis; it does not actually initiate a shutdown or restart at the guest operating system level. To be able to shut down or restart your vApps gracefully, you can use the Stop-CIVAppGuest and Restart-CIVAppGuest cmdlets, respectively. To execute properly, these cmdlets require that VMware Tools be installed and running within the virtual machines. These commands will perform the given action on each virtual machine within the vApp.

If it is determined that a vApp needs to be restarted (we recommend that you apply a power setting to the entire vApp rather than specific virtual machines), it is best to restart it gracefully:

Get-CIVApp -Name TestvApp | Restart-CIVAppGuest -Confirm:$false

You can replace Restart-CIVAppGuest with Stop-CIVappGuest in this code if you decide to shut the vApp down rather than restart it.

vApp Configuration

Set-CIVApp allows you to modify the configuration of a given vApp. Using this cmdlet, you can change settings such as Description, Name, Owner, RenewLease, RuntimeLease, and StorageLease.

In the next example, we take the TestvApp that runs three Apache virtual machines (created earlier in this chapter), rename it to something that more accurately reflects its purpose (ApachevApp), add a description stating what the vApp used to be called, and set both a 10-day storage and runtime lease:

$lease = New-TimeSpan -Days 10
$vApp = Get-CIVapp -Name "TestvApp"
$vApp | Set-CIVApp -Name "ApachevApp" -Description "Renamed from TestvApp" | `
    Set-CIVApp -StorageLease $Lease -RuntimeLease $Lease -RenewLease

vApp Networking

vApp networks are the networks defined within the vApp container that allow communication between the virtual machines within the vApp. These networks have the ability to connect to an organization network to extend communication for the virtual machines in the vApp out past the container level to either an organization-wide network or an external network.

Get-CIVAppNetwork retrieves all vApp networks found in your vCloud Director environment. You can use this cmdlet to retrieve specific types of vApp networks by using the -ConnectionType parameter, which accepts the following values: Direct, Fenced, Isolated, and Routed. You can use the -ParentOrgNetwork parameter to retrieve a list of all vApp networks connected there:

Get-CIVappNetwork -ConnectionType Routed
Get-CIVAppNetwork -ParentOrgNetwork 'Site A Intranet'

Creating new vApp networks is a little more complex in that the cmdlet, New-CIVAppNetwork, has a number of required parameters. This cmdlet can be especially helpful in automating the bulk creation of vApp networks when pulling the needed information from a CSV file (Listing 19-5).

Listing 19-5: Bulk import of vApp networks from CSV

function Add-CIVAppNetwork {
<#
.SYNOPSIS
 Bulk-import vAppNetworks from CSV
.DESCRIPTION
 This function will allow you to bulk-import vAppNetworks from CSV
.NOTES
 Headers Used in CSV: vApp,ParentOrgNetwork,NetType,Name,Description,`
 DNSSuffix,Gateway,Netmask,PrimaryDNS,SecondaryDNS,StaticIPPool
  Source:  Automating vSphere Administration
ARAMETER CSV
 Parameter used by the function to locate the import file
.EXAMPLE
 Add-CIVappNetwork -CSV c:	empvAppNetworks.csv

#>

  param(
  [Parameter(Mandatory=$True,Position=1)]
  [ValidateNotNullOrEmpty()]
  [String]$CSV
  )

  process{
  $Source = Import-Csv -Path "$CSV"
  foreach ($line in $Source) {
  $hshParamForNewCIVAppNetwk = @{
       VApp = $line.vApp
       Routed = $true
       Name = $line.Name
       Description = $line.Description
       DnsSuffix = $line.DNSSuffix
       Gateway = $line.Gateway
       Netmask = $line.Netmask
       PrimaryDns = $line.PrimaryDNS
       SecondaryDNS = $line.SecondaryDNS
       StaticIPPool = $line.StaticIPPool
  }

  Switch ($line.NetType) {
    {"Routed", "Direct" -contains $_} `
       {$hshParamForNewCIVAppNetwk["ParentOrgNetwork"] `
       = $line.ParentOrgNetwork}
    "Isolated" {$hshParamForNewCIVAppNetwk["ParentOrgNetwork"] `
       = $null}
  }
Write-Verbose "Importing vApp Network: $($line.Name) for `
$($line.vApp)"

  New-CIVAppNetwork @hshParamForNewCIVAppNetwk
}
}
}
  $hshParamForNewCIVAppNetwk = @{
       VApp = $line.vApp
       Routed = $true
       Name = $line.Name
       Description = $line.Description
       DnsSuffix = $line.DNSSuffix
       Gateway = $line.Gateway
       Netmask = $line.Netmask
       PrimaryDns = $line.PrimaryDNS
       SecondaryDNS = $line.SecondaryDNS
       StaticIPPool = $line.StaticIPPool
  }

  Switch ($line.NetType) {
    {"Routed", "Direct" -contains $_} `
    {$hshParamForNewCIVAppNetwk["ParentOrgNetwork"] = $line.ParentOrgNetwork}
    "Isolated" {$hshParamForNewCIVAppNetwk["ParentOrgNetwork"] = $null}
  }  New-CIVAppNetwork @hshParamForNewCIVAppNetwk

Modifying the vApp network allows you to update properties such as the description, DNS information, firewall, NAT, and parent organization network. It does not allow you to change the IP, gateway, or subnet mask of the network. Making changes to a vApp network involves specifying the target vApp and piping it to the Set-CIVAppNetwork cmdlet:

$vAppNetwork = Get-CIVApp -Name vApp_system_3 | Get-CIVappNetwork Internal
$vAppNetwork | Set-CIVAppNetwork -PrimaryDns '10.144.99.16' -SecondaryDns `
'10.144.99.17' | Set-CIVAppNetwork -FirewallEnabled:$true

vApp networks are easily removed from a vApp. Use extreme caution in running this cmdlet, especially if you have set the -Confirm parameter set to false:

$vAppNetwork = Get-CIVApp -Name vApp_system_3 | Get-CIVappNetwork Internal
$vAppNetwork | Remove-CIVAppNetwork -Confirm:$false

vApp Templates

vApp templates are the vApps that are found in your catalogs. In large vCloud Director environments, there may be dozens of catalogs with hundreds of templates. You can use the Get-CIVAppTemplate cmdlet to retrieve a report of all the templates that exist at several different levels within your environment. You can retrieve all vApp templates that are visible to your account by entering the cmdlet by itself:

Get-CIVAppTemplate

You can also use the function presented in Listing 19-6 to retrieve a report of all vApp templates by catalog.

Listing 19-6: vApp

function Get-vAppTemplateReport {
<#
.SYNOPSIS
 Retrieve a summary of all vApps in all catalogs
.DESCRIPTION
 Retrieves information about each vApp of every catalog in the
 environment
.NOTES
  Source:  Automating vSphere Administration
.PARAMETER Path
 Specify the file path for the CSV output
.EXAMPLE
 Get-vAppTemplateReport -Path C:TempTemplateReport.csv

#>

  param(
  [Parameter(Mandatory=$true)]
  [ValidateNotNull()]
  [String]$Path
  )

  process{
  $Results = @()
 foreach ($Catalog in (Get-Catalog)){
  foreach ($vAppTemplate in (Get-CIVappTemplate `
  -Catalog $Catalog.Name)) {
$Results += $vAppTemplate | Select-Object -Property `
Catalog, Name, Description, OrgVDC, Published, IsGoldMaster, `
StorageUsedGB, Owner, CustomizeOnInstantiate, StorageLease 
  }

  }
  $Results | Export-CSV $Path -Append `
  -NotypeInformation -NoClobber
  }
}

Additional vApp templates can be created or imported into vCloud Director. The New-CIVappTemplate cmdlet allows you to create a template from an existing vApp in vCloud Director:

Get-CIVApp 'vApp_system_3' | New-CIVAppTemplate `
     -Name 'Default Gold Linux Build' `
     -OrgVdc 'OrgVDC1' `
     -Catalog 'Full-Catalog' `
     -Description 'Suse Gold Build'

You can import virtual machines as vApps from vSphere or OVF packages from your local machine:

Import-CIVAppTemplate -SourcePath C:TempovfLogInsight.ovf `
     -Name 'Log Insight' `
     -OrgVdc 'OrgVDC1' `
     -Catalog 'Full-Catalog'

To import virtual machines as vApps from vSphere, you must first ensure that you are connected to both vCloud Director and vSphere. You can import any virtual machine from vSphere as long as you have your target information (org vDC and catalog):

$vmname = Get-VM -Name 'MGMT-LogInsight'
Import-CIVAppTemplate -VM $vmname `
     -Name 'Log Insight Management vApp' `
     -OrgVdc 'OrgVDC1' `
     -Catalog 'Full-Catalog'

Listing 19-7 shows a function that allows you to bulk-import virtual machines from vSphere into vCloud Director catalogs. To use this function, you will need to do a little preparation within your vCenter server.

Listing 19-7 leverages tags, tag descriptions, and tag categories to correctly identify and place virtual machines from your vSphere environment into vCloud Director. You will need to create a new tag category, assigned only to virtual machines, which will be used to identify the virtual machines you want to import. You then need to create at least one tag. The tag name needs to match the target org vDC; the tag description needs to be the name of the catalog where the virtual machine will be placed. Once you’ve created the tag, use it to tag all relevant virtual machines that you wish to import into vCloud Director. You can then proceed to use the function. If you need to refresh your skills on using tags, refer to the “Tags” section found in Chapter 12, “Organize Your Disaster Recovery.”

Listing 19-7: Bulk-importing VMs from vSphere

function Import-VMtoVCD {
<#
.SYNOPSIS
 Import Tagged Virtual Machines into vCD
.DESCRIPTION
 This is designed to allow users to create a Tag Category
 designated for mass importation of Virtual Machines from
 vSphere into a vCD Catalog. This requires a designated
 Tag Category along with the Tag Name being the destination
 Org name and the description being the catalog name.
.NOTES
  Source:  Automating vSphere Administration
.PARAMETER TagCategory
 This parameter specifies the virtual machine Tag Category
 that is used to determine which VMs to mass import. Any
 virtual machine tagged with a Tag from this category will
 be imported into a vCD catalog
.EXAMPLE
 Import-VMtoVCD -TagCategory vCD_Import

#>

  param(
  [Parameter(Mandatory=$True,Position=1,ValueFromPipeline=$True)]
  [ValidateNotNullOrEmpty()]
  [String]$TagCategory
  )

  process{
 # Specify the virtual machine entity
$VMs = Get-VM

# Find all virtual machines with specified Tag Assignment
$Tagged = Get-TagAssignment -Entity (Get-VM) -Category $TagCategory

# Cycle through each tagged virtual machine
foreach ($tag in $Tagged) {
$Org = Get-OrgVDC $tag.Tag.Name
$Cat = $tag.Tag.Category
$Desc = Get-Catalog $tag.Tag.Description
$VM = $VMs | ?{$_.name -eq $tag.Entity.Name}

Write-Verbose "Importing VM: [$VM] into Catalog: [$Cat] in Org [$Org]"
# Invoke the importation cmdlet
Import-CIVappTemplate `
-VM $VM `
-Name $tag.entity Entity `
-OrgVdc $Org `
-Catalog $Desc 
}
}
}

To update the name, description, or lease time of a vApp template, you can select a specific template and pipe it to the Set-CIVAppTemplate cmdlet:

$lease = New-Timespan -Days 14
Get-CIVAppTemplate -Name 'Default Gold Linux Build' | `
Set-CIVAppTemplate -StorageLease $lease | `
     Set-CIVAppTemplate -Name 'Suse Gold Current' `
     -Description 'Most Current Suse Build for Engineering'

Manage VMs

In vCloud Director, virtual machines are managed differently within a vApp compared to running solely within a vSphere environment. Virtual machines are found within the vApp containers. Unlike the -CIVApp cmdlets, the CIVM cmdlets affect only the VM specified, rather than each VM within the vApp.

New-CIVM allows you to create additional virtual machines inside an existing vApp. Start-CIVM, Stop-CIVM, Restart-CIVM, and Suspend-CIVM are all used for the power management of individual virtual machines inside a vApp. Suspend-CIVM works just like suspending a virtual machine within vSphere. If you want to freeze the state of a virtual machine to work with it later, the Suspend-CIVM cmdlet will save the entire state of the given virtual machine in a VMSS file for later use.

Power Commands

Powering on specific virtual machines within a vApp rather than powering on the entire vApp is not recommended—but sometimes it’s necessary. In those situations, you can run the following:

Get-CIVApp TestvApp | Get-CIVM -Name Apache03 | Start-CIVM

To gracefully power off or restart specific virtual machines in a vApp, you can use the Stop-CIVMGuest and Restart-CIVMGuest cmdlets, which will communicate with the guest operating system to ensure the virtual machine is powered down or restarted safely and gracefully. For example, if one of the CIVMs created earlier in this chapter, Apache03, were exhibiting issues or presenting irregular performance data and the administrators determined that it should be restarted, you would want to restart just the affected virtual machine, rather than the entire vApp and all virtual machines within it:

Get-CIVApp TestvApp | Get-CIVM -Name Apache03 | `
Restart-CIVMGuest -Confirm:$false

Start Rules

Once the vApp has been created or imported into vCloud Director, you can set start rules for the virtual machines in that vApp. Each virtual machine within a vApp has a default Start Rule of PowerOn with no start delay. If, for example, a vApp contained an Active Directory server, a database server, and an application server, you could consider setting start rules that start up the AD server at the same time as the database server, but delay the application server a given number of seconds to allow the database server to be up and running before the application tries to connect.

Although changing the start rules for our example of the three Apache virtual machines will not be beneficial at this moment, we will still use that vApp to demonstrate how these rules can be set:

$TargetvApp = Get-CIVapp TestvApp
Get-CIVAppStartRule -VApp $TargetvApp

When you run that code, you will see that this vApp has the default start rules. Using the next example code, we will set Apache04 and Apache 05 each for a delay of 20 seconds but allow Apache03 to start immediately:

$vm = Get-CIVM -Name Apache04,Apache05 -VApp $TargetvApp
$startrule = Get-CIVAppStartRule -VApp $TargetvApp -VM $vm
Set-CIVappStartRule -StartRule $startrule -StartDelaySeconds 20

vCloud Director Networks

When working in vCloud Director, you’ll deal with three types of networks:

  1. External The external network is the foundational network. This network is based on a vSphere port group, which allows all other network connectivity to flow into and out of vCloud Director organizations.
  2. Organization Organization networks, which we discussed earlier in this chapter, are networks available to all vApps within its organization. These networks sit on top of the external network, unless the organization network is internal, meaning isolated within the given organization.
  3. vApp vApp networks, also discussed earlier in this chapter, are the innermost networks within vCloud Director, found within the vApp container. These networks allow virtual machines within a vApp to communicate with one another. These networks can be backed on the organization networks if you decide to configure the vApp network that way.

Since both organization and vApp networks have been discussed in previous sections of this chapter, we will only discuss external networks here. You can retrieve a list of all the external networks of your vCloud Director environment using the Get-ExternalNetwork cmdlet:

Get-ExternalNetwork

You can also retrieve more specific results by specifying a Provider vDC:

Get-ProviderVDC 'MainpVDC' | Get-ExternalNetwork

Search-Cloud

Search-Cloud is a powerful cmdlet that allows users to search their vCloud Director environment for specific object types. You may find this cmdlet will return results faster than other Get- cmdlets in vCD.

When using this cmdlet, you may find that there isn’t a whole lot of information on what object query types can be searched for. There are several ways to get this information. The first is to try an invalid search term on the -QueryType parameter like ESX. An error message will display and ask you to “Specify one of the following enumerator names and try again.” It will then proceed to list all available enumerator names for the -QueryType parameter. Table 19-1 lists the available enumerator names.

You will notice that there are a number of objects in Table 19-1 that do not have an equivalent Get- command. Search-Cloud is especially useful with these objects, because it gives you a way to quickly view information about the object and allows you to use the vCloud API to invoke actions when needed.

Table 19-1: Available -QueryType enumerator names

ESX enumeratorESX enumeratorESX enumeratorESX enumerator
AclRuleAdminVAppTemplateHostServiceLink
AdminAllocatedExternalAddressAdminVMMediaServiceResource
AdminApiDefinitionAdminVMDiskRelationNetworkPoolStrandedItem
AdminCatalogAllocatedExternalAddressOrganizationStrandedUser
AdminCatalogItemApiDefinitionOrgNetworkTask
AdminDiskApiFilterOrgVdcVApp
AdminEventBlockingTaskOrgVdcNetworkVAppNetwork
AdminEventCBMCatalogOrgVdcResourcePoolRelationVAppOrgNetworkRelation
AdminFileDescriptorCatalogItemOrgVdcStorageProfileVAppOrgVdcNetworkRelation
AdminGroupCellPortgroupVAppTemplate
AdminMediaConditionProviderVdcVirtualCenter
AdminOrgNetworkDatastoreProviderVdcRelationProviderVdcResourcePoolRelationVm
AdminOrgVdcDiskProviderVdcStorageProfileVmDiskRelation
AdminOrgVdcStorageProfileDvSwitchResourceClassDatastore
AdminServiceEdgeGatewayResourceClassActionUser
AdminShadowVMEventResourcePool
AdminTaskExternalLocalizationResourcePoolVmList
AdminUserExternalNetworkRight
AdminVAppFileDescriptorRole
AdminVAppNetworkGroupService

For example, you might want to get additional information on the vCenter(s) attached to vCloud Director. In this situation, you would run this:

$Vc = Search-Cloud -QueryType VirtualCenter | Get-CIView

You can then perform a Get-Member to see the methods available against the object. You’ll notice that there are a number of Import and Refresh commands, as well as a number of other options. This may be useful if you want to perform actions available through the API that do not have a cmdlet available.

$vc | gm | Select Name, MemberType

Name                                MemberType
----                                ----------
Delete_Task                             Method
Equals                                  Method
Forcevimserverreconnect                 Method
Forcevimserverreconnect_Task            Method
GetHashCode                             Method
GetHostReferences                       Method
GetNetworks                             Method
GetResourcePoolList                     Method
GetStorageProfiles                      Method
GetType                                 Method
GetVIView                               Method
GetVmsList                              Method
ImportMedia                             Method
ImportVmAsVApp                          Method
ImportVmAsVAppTemplate                  Method
ImportVmIntoExistingVApp                Method
ImportVmIntoExistingVApp_Task           Method
Refresh                                 Method
RefreshStorageProfiles                  Method
RefreshStorageProfiles_Task             Method
Refresh_Task                            Method
ToString                                Method
Unregister                              Method
Unregister_Task                         Method
UpdateServerData                        Method
UpdateServerData_Task                   Method
UpdateViewData                          Method

When using the Search-Cloud cmdlet, if you do not specify which properties you want retrieved using the -Property parameter, the result will display all properties of the objects returned. The -Filter parameter can be used to narrow the search results. Note that you can add multiple filter criteria on each search. The criteria must be separated by a semicolon (;). For more information on the filter syntax, refer to the vCloud API Programming Guide.

You also can search for a particular org vDC. In our next example, we’ll search for an org vDC named OrgVDC1:

Search-Cloud -QueryType OrgVdcNetwork -Filter 'VdcName==OrgVDC1'

That code returns all properties of OrgVDC1. You can simplify the results by using the -Property parameter mentioned earlier:

Search-Cloud -QueryType OrgVdcNetwork -Filter 'VdcName==OrgVDC1' `
-Property 'Name', 'DnsSuffix', 'DefaultGateway', 'Dns1'

The return now presents only the data specified.

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

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