In this chapter, you will learn to:
One of the focal points and key use cases of PowerCLI is the automation of tasks that are needed either as part of a disaster recovery (DR) solution or as part of an automated deployment solution that can be used repeatedly—you’ll be safe in the knowledge that scripts will produce consistent and easy-to-use solutions.
This chapter will take you through some common areas automated within vSphere, starting at the beginning of the virtual infrastructure. Not only will we show you how to automate the build, but we’ll also provide examples of export scripts that will help you export information into a centralized area. The exported data will then be ready for use in reports or for the import process of another setup.
As part of the overall virtual infrastructure, one of the first products you will need to install is the vCenter Server, or Virtual Infrastructure Server. Although this cannot be done directly using PowerCLI cmdlets, you can use the automated nature of PowerCLI and PowerShell to automate the vCenter Server installation.
The key thing to remember while reading this chapter—and indeed the entire book—is that PowerShell reaches past the virtual infrastructure. It can be used to manage most areas of the Windows-based operating system and application set. PowerCLI is purely an addition to PowerShell that allows you to manage the virtual infrastructure.
To automate the installation of vCenter Server and its respective components, including the vSphere Client, Update Manager, Converter, and the corresponding databases, you will need the install media as well as various other items, such as the correct version of the .NET Framework and Windows installed on the server. The components you choose to install will depend on your infrastructure and the type of database you are going to use with your vCenter Server install.
Before you attempt to create an automated installation, be sure that:
When installing vCenter Server manually, you first download the media, and then run through a series of wizards, ensuring that each step within the wizard is correctly configured before completing the installation and waiting for the wizard to install vCenter Server. This process can become cumbersome if the installation needs to be repeated multiple times, and mistakes can be made that could cause key configured items to be incorrect.
Once you know what properties are required to perform an automated (also known as silent) install, you will be able to begin writing a script that can be reused as many times as desired. One key to creating a successful installation script that can be reused is to use variables for property values. This allows the user to use CSV files, additional scripts, and other methods to specify different values for each property in subsequent deployments without having to manually edit the installation script.
Generally, scripts have a few key items: property variables for repeatability, the location of the installation media, installer switches that specify how the installer will act, and a line that creates the installation string to be run.
The automated vCenter installation scripts vary slightly depending on the version of vCenter used (requirements and features can change between versions). The properties defined in Listing 1-1 are configured for use with vCenter Server 6. If you are using a previous version of vCenter Server for your install, the properties may be different. However, the method of invoking the vCenter installation remains the same.
In this example, we are installing vCenter Server 6 using a remote SQL Server 2014 database. vCenter Server 6 can also install using an internal vPostgres database. To ensure a successful installation, we specify values for all of the properties required for the type of installation we are performing.
As you can see in Listing 1-1, once values have been given to each of the variables for the required properties, it is only a matter of creating the argument string that will be passed to the installer. Using a script like this ensures each installation is configured correctly and no mistakes are made.
Before running the sample script in Listing 1-1, we ensured that all prerequisites and installation requirements were completed. Listing 1-1 shows how you might automate an installation of vCenter Server.
Listing 1-1: Sample script for an automated installation of vCenter Server
#Install vCenter Server unattended
$VCMedia = "D:vCenter-Server"
$SVC_USER = "WIN_VCENTER6vCenter"
$SVC_PASS = "VMw@re123"
$FQDN = "MGMT-VC6.contoso.com"
$VcIP = "10.144.99.16"
#Database Info
$TYPE = "external"
$DSN = "vCenter"
$USER = "vCenter"
$PASS = "VMw@re123"
$SSO_DOMAIN = "vsphere.local"
$SSO_PASS = "VMw@re123!"
$SSO_SITE ="MY_SITE"
# Install vCenter
Write-Host "Installing vCenter"
$vars = "/i `"$VCmediaVMware-vCenter-Server.msi`" "
$vars += "/l*e `"c: empvCenterinstall.txt`" /qr "
$vars += "LAUNCHED_BY_EXE=0 FQDN=`"$FQDN`" "
$vars += "INSTALL_TYPE=embedded "
$vars += "DB_TYPE=$Type DB_DSN=`"$DSN`" "
$vars += "DB_USER=`"$USER`" "
$vars += "DB_PASSWORD=`"$PASS`" "
$vars += "INFRA_NODE_ADDRESS=`"$vCIP`" "
$vars += "VC_SVC_USER=`"$SVC_USER`" "
$vars += "VC_SVC_PASSWORD=`"$SVC_PASS`" "
$vars += "SSO_DOMAIN=`"$SSO_DOMAIN`" "
$vars += "SSO_PASSWORD=`"$SSO_PASS`" "
$vars += "SSO_SITENAME=`"$SSO_SITE`" "
Start-Process msiexec -ArgumentList $vars –Wait
Not all vCenter Servers are installed on Windows machines. VMware has released a virtual appliance known as the vCenter Server Appliance (vCSA) that can be used in place of a Windows vCenter. This option is compelling to many users because it does not require a Microsoft Windows license, and with each new release it is continuing to increase the size of environment it can handle.
Previous versions of the vCSA could be deployed using the Deploy OVF Template button within the C# client. However, with vCSA 6 this option is no longer possible. Luckily, we still have a few other options for deploying it. Along with the installer files, vCSA 6 has a command-line tool packaged in the installation media. The command-line tool leverages the use of a JavaScript Object Notation (JSON) configuration file and the OVF Tool to deploy the virtual appliance. Listing 1-2 shows an example of how we can use PowerCLI to configure the JSON configuration file and deploy the vCenter Server appliance.
Leveraging features found in PowerShell version 3 and later, we are able to convert the vCSA configuration template JSON file and convert it into a PowerShell object that we can then manipulate for our deployment purposes. Once the JSON file is converted into a PowerShell object, we can easily go through each property of the object and set its value. Once we have finished setting all the properties necessary for deployment, we can convert the PowerShell object back into a JSON file and use it to deploy the vCenter Server appliance. Figure 1-1 shows what is returned during the import process.
Listing 1-2: Sample script for an automated installation of the vCenter Server appliance
# Deploy vCSA6 using vCSA-Deploy
# Convert JSON file to PowerShell object
$ConfigLoc = "D:vcsa-cli-installer emplatesfull_conf.json"
$Installer = "D:vcsa-cli-installerwin32vcsa-deploy.exe"
$updatedconfig = "C:Tempconfiguration.json"
$json = (Get-Content -Raw $ConfigLoc) | ConvertFrom-Json
# vCSA system information
$json.vcsa.system."root.password"="VMw@re123"
$json.vcsa.system."ntp.servers"="198.60.73.8"
$json.vcsa.sso.password = "VMw@re123"
$json.vcsa.sso."site-name" = "Primary-Site"
# ESXi Host Information
$json.deployment."esx.hostname"="10.144.99.11"
$json.deployment."esx.datastore"="ISCSI-SSD-900GB"
$json.deployment."esx.username"="root"
$json.deployment."esx.password"="VMw@re123"
$json.deployment."deployment.option"="tiny"
$json.deployment."deployment.network"="VM Network"
$json.deployment."appliance.name"="Primary-vCSA6"
# Database connection
$json.vcsa.database.type="embedded"
# Networking
$json.vcsa.networking.mode = "static"
$json.vcsa.networking.ip = "10.144.99.19"
$json.vcsa.networking.prefix = "24"
$json.vcsa.networking.gateway = "10.144.99.1"
$json.vcsa.networking."dns.servers"="10.144.99.5"
$json.vcsa.networking."system.name"="10.144.99.19"
$json | ConvertTo-Json | Set-Content -Path "$updatedconfig"
Invoke-Expression "$installer $updatedconfig"
Additional components, such as the vCenter Client or Update Manager, can also be installed in an automated fashion. We can deploy Update Manager the same way we deployed the Windows vCenter Server (see Listing 1-3).
Listing 1-3: Sample script for a silent install of the vSphere Client
# Install vCenter Client
Write-Host "Installing vCenter Client"
$VIMedia = "D:vsphere-ClientVMware-viclient.exe"
Start-Process $VIMedia -ArgumentList '/q /s /w /V" /qr"' -Wait -Verb RunAs
vSphere Update Manager (VUM) deployments can also be automated in a similar fashion as vCenter Server. Update Manager can leverage a local database, but to maintain consistency with how we deployed vCenter Server, we will be deploying to a remote SQL database. Listing 1-4 shows how you can automate the deployment of vSphere Update Manager 6.
Listing 1-4: Sample script for an automated installation of vSphere Update Manager
# Media
$VUMMedia = "D:updateManager"
# Database
$DSN = "VUM"
$User = "vCenter"
$Pass = "VMw@re123"
# vCenter
$vCenter = "10.144.99.16"
$port = "80"
$vCAdmin = "[email protected]"
$vCAdmin_Pass = "VMw@re123"
$vArgs = "/V`" /qr /L*v c: empvmvci.log "
$vArgs += "WARNING_LEVEL=0 VCI_DB_SERVER_TYPE=Custom "
$vArgs += "DB_DSN=$DSN DB_USERNAME=$user "
$vArgs += "DB_PASSWORD=$pass "
$vArgs += "VMUM_SERVER_SELECT=$vCenter "
$vArgs += "VC_SERVER_IP=$vCenter "
$vArgs += "VC_SERVER_PORT=$port "
$vArgs += "VC_SERVER_ADMIN_USER=$vCAdmin "
$vArgs += "VC_SERVER_ADMIN_PASSWORD=$vCAdmin_Pass`""
$vars = @()
$vars += '/s'
$vars += '/w'
$vars += $vArgs
Start-Process -FilePath $VUMMediaVMware-UpdateManager.exe -ArgumentList $vars
VMware supports more automated installation options and parameters, such as installing a linked mode vCenter Server, and maintains an online installation document here:
https://www.vmware.com/support/pubs/vsphere-esxi-vcenter-server-pubs.html
Two types of folders are supported in vSphere. From within the Hosts and Clusters view, you are able to create folders at any point under the datacenter level. These are commonly known as yellow folders and can be used throughout the infrastructure to organize the clusters, hosts, and VMs in a logical view.
Blue folders can be seen in the VMs and Templates view. Use these folders to more accurately reflect the layout of your VMs from a logical point of view. For example, you can create folders based on departments (such as Finance
, Legal
, and Customer Services
) or by function (Internet
, Active Directory
, File Servers
, Print Servers
, Databases
), or any other view that makes sense to your organization. Blue folders could also be used to reflect a security function and used to group the VMs into folders that only certain people can access. Once you create the folder, you can use it to grant access to various vCenter Server permissions.
You can initially create your folder structure when you create your new VMs; create your templates and move them into the appropriate folder. Another way of creating the folder structure is to plan the layout in a comma-separated value (CSV) file. This type of plan can easily be created in an Excel document, as shown in Figure 1-2, and then exported to the CSV format needed to create the virtual folder structure.
In the example CSV file we created, there are two columns. The first column, Name, is used to define the name of the folder that you wish to create. The second column, Path, is used to show the path to where this folder is to be created in vCenter Server. As seen in Figure 1-2, in the Path column all entries begin with vm
. This folder will not be created but is used by the underlying application programming interface (API). Once you have created the CSV file that contains the layout of your folder structure, a script can easily read your CSV file and create the structure using the code shown in Listing 1-5.
Listing 1-5: Using a CSV file to create a vCenter file structure
function Import-Folders {
<#
.SYNOPSIS
Imports a csv file of folders into vCenter Server and
creates them automatically.
.DESCRIPTION
The function will import folders from CSV file and create
them in vCenter Server.
.NOTES
Source: Automating vSphere Administration
.PARAMETER FolderType
The type of folder to create
.PARAMETER DC
The Datacenter to create the folder structure
.PARAMETER Filename
The path of the CSV file to use when importing
.EXAMPLE
Import-Folders -FolderType "Blue" -DC "DC01" `
-Filename "C:BlueFolders.csv"
.EXAMPLE
Import-Folders -FolderType "Yellow" -DC "Datacenter"
-Filename "C:YellowFolders.csv"
#>
param(
[String]$FolderType,
[String]$DC,
[String]$Filename
)
process{
$vmfolder = Import-Csv $filename | `
Sort-Object -Property Path
If ($FolderType -eq "Yellow") {
$type = "host"
} Else {
$type = "vm"
}
foreach($folder in $VMfolder){
$key = @()
$key = ($folder.Path -split "\")[-2]
if ($key -eq "vm") {
Get-Datacenter $dc | Get-Folder $type | `
New-Folder -Name $folder.Name
} else {
Get-Datacenter $dc | Get-Folder $type | `
Get-Folder $key | `
New-Folder -Name $folder.Name
}
}
}
}
Import-Folders -FolderType "blue" -DC "DC01" `
-Filename "C:BlueFolders.csv"
Both yellow and blue folder views can be exported to a CSV file. You will find this technique useful when you are rebuilding your vCenter Server from scratch or creating a DR replica of the current virtual infrastructure.
The script in Listing 1-6 can be used to export either a blue or a yellow folder structure to a CSV. It can also be used to export the location of the current VMs, ensuring a replicated location when you reimport the structure.
Listing 1-6: Exporting a vCenter structure to a CSV file
filter Get-FolderPath {
<#
.SYNOPSIS
Collates the full folder path
.DESCRIPTION
The function will find the full folder path returning a
name and path
.NOTES
Source: Automating vSphere Administration
#>
$_ | Get-View | % {
$row = "" | select Name, Path
$row.Name = $_.Name
$current = Get-View $_.Parent
$path = $_.Name
do {
$parent = $current
if($parent.Name -ne "vm"){
$path = $parent.Name + "" + $path
}
$current = Get-View $current.Parent
} while ($current.Parent -ne $null)
$row.Path = $path
$row
}
}
function Export-Folders {
<#
.SYNOPSIS
Creates a csv file of folders in vCenter Server.
.DESCRIPTION
The function will export folders from vCenter Server
and add them to a CSV file.
.NOTES
Source: Automating vSphere Administration
.PARAMETER FolderType
The type of folder to export
.PARAMETER DC
The Datacenter where the folders reside
.PARAMETER Filename
The path of the CSV file to use when exporting
.EXAMPLE
Export-Folders -FolderType "Blue" -DC "DC01" -Filename `
"C:BlueFolders.csv"
.EXAMPLE
Export-Folders -FolderType "Yellow" -DC "Datacenter"
-Filename "C:YellowFolders.csv"
#>
param(
[String]$FolderType,
[String]$DC,
[String]$Filename
)
Process {
If ($Foldertype -eq "Yellow") {
$type = "host"
} Else {
$type = "vm"
}
$report = @()
$report = Get-Datacenter $dc | Get-Folder $type | `
Get-Folder | Get-FolderPath
$report | Foreach-Object {
if ($type -eq "vm") {
$_.Path = ($_.Path).Replace($dc + "","$type")
}
}
$report | Export-Csv $filename -NoTypeInformation
}
}
function Export-VMLocation {
<#
.SYNOPSIS
Creates a csv file with the folder location of each VM.
.DESCRIPTION
The function will export VM locations from vCenter Server
and add them to a CSV file.
.NOTES
Source: Automating vSphere Administration
.PARAMETER DC
The Datacenter where the folders reside
.PARAMETER Filename
The path of the CSV file to use when exporting
.EXAMPLE
Export-VMLocation -DC "DC01" `
-Filename "C:VMLocations.csv"
#>
param(
[String]$DC,
[String]$Filename
)
Process {
$report = @()
$report = Get-Datacenter $dc | Get-VM | Get-FolderPath
$report | Export-Csv $filename -NoTypeInformation
}
}
Export-Folders "Blue" "DC01" "C:BlueFolders.csv"
Export-VMLocation "DC01" "C:VMLocation.csv"
Export-Folders "Yellow" "DC01" "C:YellowFolders.csv"
You can import an existing blue or yellow folder structure into vCenter Server using the Import-Folders
function previously shown in Listing 1-5. You can also choose if you would like your VMs moved back into their correct blue folders by using the Import-VMLocation
function, as shown in Listing 1-7.
Listing 1-7: Importing VMs to their blue folders
function Import-VMLocation {
<#
.SYNOPSIS
Imports the VMs back into their Blue Folders based on
the data from a csv file.
.DESCRIPTION
The function will import VM locations from CSV File
and add them to their correct Blue Folders.
.NOTES
Source: Automating vSphere Administration
.PARAMETER DC
The Datacenter where the folders reside
.PARAMETER Filename
The path of the CSV file to use when importing
.EXAMPLE
Import-VMLocation -DC "DC01" -Filename "C:VMLocations.csv"
#>
param(
[String]$DC,
[String]$Filename
)
Process {
$Report = @()
$Report = Import-Csv $filename | Sort-Object -Property Path
foreach($vmpath in $Report){
$key = @()
$key = Split-Path $vmpath.Path | Split-Path -Leaf
Move-VM (Get-Datacenter $dc `
| Get-VM $vmpath.Name) `
-Destination (Get-Datacenter $dc | Get-Folder $key)
}
}
}
Import-VMLocation "DC01" "C:VMLocation.csv"
The authorization to perform tasks in your virtual infrastructure is controlled by a role-based access control (RBAC) system. A vCenter Server administrator can specify in great detail which users or groups can perform which tasks on which objects. RBAC systems are defined using three key concepts:
Privileges are found in the vSphere Web Client. When using the Roles wizard, you are able to add new privileges. The privileges are listed in Figure 1-3.
How many privileges are there? Think of any action you have ever performed in the vCenter Client. Think about the actions you have not yet come across or used in your everyday job. Now add them up, and you will have some idea of how many privileges there are in vCenter Server. Luckily, we are able to use PowerCLI to come up with a scientific answer for this question. You can easily list all privileges available to assign to a user through vCenter Server using the Get-VIPrivilege
cmdlet:
[vSphere PowerCLI] C:> Get-VIPrivilege | Select Name, Description
Name Description
---- -----------
Anonymous The only privilege held by sessions ...
View Visibility without read access to an...
Read Grants read access to an entity
Manage custom attributes Add, remove, and rename custom attri...
Set custom attribute Set the value of a custom attribute ...
Log event Log a user-defined event on an object
Cancel task Cancel a running task
Licenses Manage licenses
Diagnostics Export diagnostic data
Settings Edit global settings
Act as vCenter Server Act as the vCenter Server
Capacity planning Discover and convert physical host t...
Script action Schedule an external script action
Proxy Add or remove endpoints to or from t...
Disable methods Operations are disabled in vCenter
Enable methods Operations are enabled in vCenter
Service managers Access the directory service
Health Access the health of vCenter group
…………
We purposely truncated the output listing due to the large number of privileges available. You can count the number of privileges available for assigning to your roles and users or groups by using the Measure-Object
cmdlet:
[vSphere PowerCLI] C:> Get-VIPrivilege | Measure-Object
Count : 360
Average :
Sum :
Maximum :
Minimum :
Property :
You can also use the Get-VIPrivilege
cmdlet to show only the privileges available to certain sets of objects like a host:
[vSphere PowerCLI] C:> Get-VIPrivilege -Name *Host* `
| Select Name, Description -Unique
Name Description
---- -----------
Host operation Change the host member of a distributed ...
Add standalone host Add a standalone host
Add host to cluster Add a host to a cluster
Remove host Remove a host
Move cluster or standalone host Move a cluster or standalone host
Move host Move a host between clusters
Add host to vCenter Bring the host under vCenter management
Host USB device Add, remove or edit a virtual USB device...
Host Host
Host profile Host profile
Host Host
You can view which groups (collections of privileges) are available by using the Get-VIPrivilege
cmdlet with the -PrivilegeGroup
parameter, as shown here:
[vSphere PowerCLI] C:> Get-VIPrivilege -PrivilegeGroup | `
Select Name, Description
Name Description
---- -----------
System System
Global Global
Folder Folder
Datacenter Datacenter
Datastore Datastore
Network Networks
Distributed switch Distributed switch
dvPort group dvPort groups
Host Host
Inventory Host inventory
vSphere Replication vSphere Replication operations
Configuration Host configuration
Local operations Host local operations
CIM CIM
Virtual machine Virtual machine
Inventory Virtual machine inventory
Interaction Virtual machine interaction
Guest Operations Operations in a virtual machine guest op...
Configuration Virtual machine configuration
Snapshot management Virtual machine snapshot management
vSphere Replication vSphere Replication configuration
Provisioning Virtual machine provisioning
Service configuration Virtual machine service configuration
VRMPolicy Virtual Rights Management Policy
Resource Resource allocation
Alarms Alarms
Tasks Tasks
Scheduled task Scheduled task
Sessions Sessions
Performance Performance
Permissions Permissions
Extension Extensions
vApp Privileges related to vApps
Host profile Host profile
ESX Agent Manager ESX Agent Manager
Datastore cluster Datastore cluster
Certificates Certificates
vCenter Inventory Service Inventory Service
vCenter Inventory Service Tagging Create and Assign Tags to Objects in the...
Provider Provider
Storage views Storage views
vService vService management
Profile-driven storage Profile-driven storage
AutoDeploy Auto Deploy
Image Profile Image Profile
Rule Rule
RuleSet Rule sets
Host Host
TransferService TransferService
Content Library Content Library
A number of default roles come preconfigured with the installation of vCenter Server (see Figure 1-4). By selecting a role in the vSphere Web Client, you can see the list of privileges given to that role (on the right side). Each privilege category may be expanded and collapsed to see all the privileges set for the current role.
You can see an overview of the predefined roles by using the Get-VIRole
cmdlet, as shown here:
[vSphere PowerCLI] C:> Get-VIRole | Select Name, Description
Name Description
---- -----------
NoAccess Used for restricting granted access
Anonymous Not logged-in user (cannot be granted)
View Visibility access (cannot be granted)
ReadOnly See details of objects, but not make...
Admin Full access rights
VirtualMachinePowerUser Provides virtual machine interaction...
VirtualMachineUser Provides virtual machine interaction...
ResourcePoolAdministrator Supports delegated resource management
VMwareConsolidatedBackupUser Used by the Consolidated Backup utility
DatastoreConsumer Assigned to datastores to allow crea...
NetworkConsumer Assigned to networks to allow associ...
InventoryService.Tagging.TaggingAdmin InventoryService.Tagging.TaggingAdmin
com.vmware.Content.Admin Provides full access to Content Libr...
Now that you know that a role is a group of privileges and you’ve learned to use the Get-VIPrivilege
and Get-VIRole
cmdlets, we want to introduce you to New-VIRole
. You can use the New-VIRole
cmdlet with Get-VIPrivilege
to define a new role. You can define your own group of privileges, which can later be assigned to your users. An example is shown in Listing 1-8; you can see the results in the vCenter Client, as shown in Figure 1-5.
Listing 1-8: Creating a new role
New-VIRole `
-Name 'New Custom Role' `
-Privilege (Get-VIPrivilege `
-PrivilegeGroup "Interaction","Provisioning")
A new role can also be created at a granular level. First, choose the privileges you want to use:
$Priv = @()
$MyPriv = "Profile", "VCIntegrity.Baseline", `
"VApp.Move", "Profile.Clear"
And then add each of them into an array:
Foreach ($CustPriv in $MyPriv){
$Priv += Get-VIPrivilege | Where {$_.Id -eq $CustPriv}
}
You can then use the array of privileges to apply your specific permissions to the new role:
New-VIRole "New selected Role" -Privilege $Priv
Now that you have defined your roles, you can start using them. Until now, you have only been working with roles and privileges. Once you define what you want your user to be able to do, you need to add users and grant them access to the roles. You can then enable them to start using the features of the vSphere Web Client.
A role or privilege can be assigned to any of the objects within a vCenter Server. Each of the objects can be defined by different roles or privileges. Together, objects, roles, and privileges make up a permission set. Permission sets can be inherited; inheritance ensures that each object underneath a datacenter, cluster, resource pool, or folder gives the users the correct access privileges.
So it comes as no great surprise that, when adding a permission through PowerCLI, you must consider three areas:
In the code that follows, we grant a user (VSPHERE.localUser01
) access to New Custom Role
at the datacenter level:
New-VIPermission -Role 'New Custom Role' `
-Principal 'VSPHERE.localUser01' `
-Entity (Get-Datacenter)
After you’ve set up and tested individual permissions, you can export them to a readable, importable format. This eases multiple installations and the transfer of permissions to further vCenter Servers, and ensures consistency as well. We’ll show you how next.
The script in Listing 1-9 exports all relevant information into a CSV file, which can later be used to import them back into the same or a different vCenter Server. Exporting the permissions can be a great way to satisfy a security audit or ensure the relevant departments or users have the correct permissions.
Listing 1-9: Exporting permissions
function Export-PermissionsToCSV {
<#
.SYNOPSIS
Exports all Permissions to CSV file
.DESCRIPTION
The function will export all permissions to a CSV
based file for later import
.NOTES
Source: Automating vSphere Administration
.PARAMETER Filename
The path of the CSV file to be created
.EXAMPLE
Export-PermissionsToCSV -Filename "C:TempPermissions.csv"
#>
param(
[String]$Filename
)
Process {
$folderperms = Get-Datacenter | Get-Folder | Get-VIPermission
$vmperms = Get-Datacenter | Get-VM | Get-VIPermission
$permissions = Get-Datacenter | Get-VIpermission
$report = @()
foreach($perm in $permissions){
$row = "" | select EntityId, Name, Role, `
Principal, IsGroup, Propagate
$row.EntityId = $perm.EntityId
$Foldername = (Get-View -Id $perm.EntityId –Property Name).Name
$row.Name = $foldername
$row.Principal = $perm.Principal
$row.Role = $perm.Role
$row.IsGroup = $perm.IsGroup
$row.Propagate = $perm.Propagate
$report += $row
}
foreach($perm in $folderperms){
$row = "" | select EntityId, Name, Role, `
Principal, IsGroup, Propagate
$row.EntityId = $perm.EntityId
$Foldername = (Get-View -Id $perm.EntityId –Property Name).Name
$row.Name = $foldername
$row.Principal = $perm.Principal
$row.Role = $perm.Role
$row.IsGroup = $perm.IsGroup
$row.Propagate = $perm.Propagate
$report += $row
}
foreach($perm in $vmperms){
$row = "" | select EntityId, Name, Role, `
Principal, IsGroup, Propagate
$row.EntityId = $perm.EntityId
$Foldername = (Get-View -Id $perm.EntityId –Property Name).Name
$row.Name = $foldername
$row.Principal = $perm.Principal
$row.Role = $perm.Role
$row.IsGroup = $perm.IsGroup
$row.Propagate = $perm.Propagate
$report += $row
}
$report | Export-Csv $Filename -NoTypeInformation
}
}
Export-PermissionsToCSV -Filename "C:TempPermissions.csv"
It is equally important to be able to import the permissions back into your vCenter Server. To do so, you can use the script in Listing 1-10. Understand that because of the way that permissions are created and stored in vCenter, you can only import back into the vCenter from which you exported the permissions.
Listing 1-10: Importing permissions
function Import-Permissions {
<#
.SYNOPSIS
Imports all Permissions from CSV file
.DESCRIPTION
The function will import all permissions from a CSV
file and apply them to the vCenter Server objects.
.NOTES
Source: Automating vSphere Administration
.PARAMETER Filename
The path of the CSV file to be imported
.EXAMPLE
Import-Permissions -DC -Filename "C:TempPermissions.csv"
#>
param(
[String]$Filename
)
process {
$permissions = @()
$permissions = Import-Csv $Filename
foreach ($perm in $permissions) {
$entity = (Get-View –Id $perm.EntityId –Property Name).MoRef
$object = Get-Inventory -Name $perm.Name
if($object.Count){
$object = $object | where {$_.Id -eq $perm.EntityId}
}
if($object){
switch -Wildcard ($perm.EntityId)
{
Folder* {
$entity.Type = "Folder"
$entity.value = $object.Id.TrimStart("Folder-")
}
VirtualMachine* {
$entity.Type = "VirtualMachine"
$entity.value = $object.Id.TrimStart("VirtualMachine-")
}
ClusterComputeResource* {
$entity.Type = "ClusterComputeResource"
$entity.value = `
$object.Id.TrimStart("ClusterComputeResource-")
}
Datacenter* {
$entity.Type = "Datacenter"
$entity.value = $object.Id.TrimStart("Datacenter-")
}
}
$setperm = New-Object VMware.Vim.Permission
$setperm.principal = $perm.Principal
if ($perm.isgroup -eq "True") {
$setperm.group = $true
} else {
$setperm.group = $false
}
$setperm.roleId = (Get-VIRole $perm.Role).id
if ($perm.propagate -eq "True") {
$setperm.propagate = $true
} else {
$setperm.propagate = $false
}
$AuthMan = Get-View -Id `
'AuthorizationManager-AuthorizationManager'
Write-Host "Setting Permissions on `
$($perm.Name) for $($perm.principal)"
$AuthMan.SetEntityPermissions($entity, $setperm)
}
}
}
}
Import-Permissions -DC "DC01" -Filename "C:TempPermissions.csv"
vCenter Server has a hierarchical management structure similar to that of Microsoft Active Directory. Three main containers can be added to vCenter Server:
Datacenters are generally created as part of the initial setup process. The setup can be automated by using the following code, which will create a datacenter called Boston and store it in a variable. The Datacenter
object held within the variable can then be referred to later in the code as you create clusters or folders:
$BostonDC = New-Datacenter -Name Boston -Location Datacenters
Clusters are more complex than datacenters; there are many configurable items available for a new cluster. Consider the options the vSphere Web Client gives us: the normal cluster options as well as configuration options for VMware High Availability (HA), VMware Distributed Resource Scheduler (DRS), VMware Enhanced VMotion Compatibility (EVC), and VMware Distributed Power Management (DPM).
To create a new cluster in the Boston datacenter you created earlier, you can use the following code:
$ProductionCluster = New-Cluster -Location $BostonDC `
-Name "Production"
This code line gives you the basic settings. The sections that follow discuss the additional cluster settings available to you.
When configured in a cluster, VMware HA gives you many advantages, including the following:
Much like the configuration of a cluster through the vSphere Web Client, you can configure HA within a cluster either as part of the initial cluster setup or you can alter an existing cluster object. For example, to configure a new cluster named Production
with HA enabled and an HA failover level of 1 physical host failure and the HA Restart Priority as Medium, you would use the code in Listing 1-11.
Listing 1-11: Enabling HA with a failover host level and restart priority on a new cluster
$ProductionCluster = New-Cluster `
-Location $BostonDC `
-Name "Production" `
-HAEnabled -HAAdmissionControlEnabled `
-HAFailoverLevel 1 `
-HARestartPriority "Medium"
To complete this same action on an existing cluster, you first need to retrieve the cluster as an object and then push it down the pipeline into the Set-Cluster
cmdlet, as shown in Listing 1-12.
Listing 1-12: Enabling HA with a failover host level and restart priority on an existing cluster
Get-Cluster `
-Location $BostonDC `
-Name "Production" | `
Set-Cluster -HAEnabled $true `
-HAAdmissionControlEnabled $true `
-HAFailoverLevel 1 `
-HARestartPriority "Medium"
VMware DRS is a configuration made at the cluster level of the vCenter Server environment that balances VM workloads with available host resources. With VMware DRS, you are able to define the rules for allocation of physical resources among the VMs. DRS can be configured for manual or automatic control. If the workload on one or more VMs drastically changes, DRS redistributes the VMs among the physical servers to ensure the resources are available where needed. Much like HA, DRS can be configured as part of the initial cluster setup or as an alteration to an existing cluster object. For example, to configure a new Production
cluster with DRS enabled and a DRS automation level of FullyAutomated
with DRSMode
set to FullyAutomated
, you would use the code in Listing 1-13.
Listing 1-13: Configuring DRS on a new cluster
$ProductionCluster = New-Cluster "Production" `
-Location $BostonDC `
-DrsEnabled `
-DrsAutomationLevel "FullyAutomated" `
-Confirm:$false
To complete this same action on an existing cluster, you would again need to retrieve the cluster object and push the object through the pipe into the Set-Cluster
cmdlet, as shown in Listing 1-14.
Listing 1-14: Configuring DRS on an existing cluster
Get-Cluster -Location $BostonDC `
-Name "Production" | Set-Cluster `
-DrsEnabled $true `
-DrsAutomationLevel "FullyAutomated" `
-Confirm:$false
EVC allows you to add multiple hosts with different CPU architectures to your cluster. EVC will, for example, allow you to add older hosts with Intel processors to a cluster that includes hosts with newer Intel processors. It does this by setting a mask on the VMs and ensuring the instruction sets are the same for both sets of hosts. Unfortunately, at this point in time VMware does not include either a PowerCLI cmdlet or a method to enable this feature programmatically. Therefore, configuring EVC is outside the scope of this book.
DPM provides cost savings by dynamically consolidating VMs onto fewer hosts during periods of low usage. Once the VMs are consolidated onto fewer hosts, the remaining hosts that are no longer hosting any VMs are powered off to save power. Once utilization starts to increase, the vSphere Server will power these hosts back on as needed.
While there are currently no options to enable DPM through the native cmdlets that are provided with PowerCLI, you can address the API and create your own function to enable DPM. For more information about using the SDK/API or Project Onyx, read Chapter 18, “The SDK.”
Listing 1-15 shows how you can enable DPM on a cluster.
Listing 1-15: Configuring DPM on a cluster
function Set-DPM {
<#
.SYNOPSIS
Enables Distributed Power Management on a cluster
.DESCRIPTION
This function will allow you to configure
DPM on an existing vCenter Server cluster
.NOTES
Source: Automating vSphere Administration
.PARAMETER Cluster
The cluster on which to set DPM configuration
.PARAMETER Behavior
DPM Behavior, this can be set to "off", "manual"
or "Automated", by default it is "off"
.EXAMPLE
Set-DPM -Cluster "Cluster01" -Behavior "Automated"
#>
param(
[String]$Cluster,
[String]$Behavior
)
Process {
switch ($Behavior) {
"Off" {
$DPMBehavior = "Automated"
$Enabled = $false
}
"Automated" {
$DPMBehavior = "Automated"
$Enabled = $true
}
"Manual" {
$DPMBehavior = "Manual"
$Enabled = $true
}
default {
$DPMBehavior = "Automated"
$Enabled = $false
}
}
$clus = Get-Cluster $Cluster | Get-View –Property Name
$spec = New-Object VMware.Vim.ClusterConfigSpecEx
$spec.dpmConfig = New-Object VMware.Vim.ClusterDpmConfigInfo
$spec.DpmConfig.DefaultDpmBehavior = $DPMBehavior
$spec.DpmConfig.Enabled = $Enabled
$clus.ReconfigureComputeResource_Task($spec, $true)
$clus.UpdateViewData("ConfigurationEx")
New-Object -TypeName PSObject -Property @{Cluster = $clus.Name; DPMEnabled = $clus.ConfigurationEx.DpmConfigInfo.Enabled; DefaultDpmBehavior = $clus.ConfigurationEx.DpmConfigInfo.DefaultDpmBehavior}
}
}
Set-DPM -Cluster "Cluster01" -Behavior "Automated"
Licensing is one of the first areas that will be critical to setting up a new host. Without a valid license, you can manage and use your host-to-host VMs for a maximum of 60 days.
You may be surprised to learn that there are no cmdlets to help with licensing ESX hosts or even viewing the current license details. However, the licensing information is available through the Get-View
cmdlet, and you can manipulate the SDK to perform the actions necessary to both view license information and set the license key for your hosts. You can write functions to help you deal with these cmdlets and make them a little friendlier than the SDK code.
To make things easier, you can use the functions we’ll show you next to list all license keys registered on the vCenter Server and also to set a license key on a host. The Get-LicenseKey
function in Listing 1-16 lists all existing license keys.
Listing 1-16: Retrieving license key information from vCenter Server
function Get-LicenseKey {
<#
.SYNOPSIS
Retrieves License Key information
.DESCRIPTION
This function will list all license keys added to
vCenter Server
.NOTES
Source: Automating vSphere Administration
.EXAMPLE
Get-LicenseKey
#>
Process {
$servInst = Get-View ServiceInstance
$licMgr = Get-View $servInst.Content.licenseManager
$licMgr.Licenses
}
}
Get-LicenseKey
Each of the existing license keys will be returned in an output listing like this:
LicenseKey : 00000-00000-00000-00000-00000
EditionKey : eval
Name : Product Evaluation
Total : 0
Used :
CostUnit :
Properties : {Localized}
Labels :
DynamicType :
DynamicProperty :
LicenseKey : AAAAA-BBBBB-CCCCC-DDDDD-EEEEE
EditionKey : vc.standard.instance
Name : VMware vCenter Server 6 Standard
Total : 16
Used : 1
CostUnit : server
Properties : {LicenseInfo, ProductName, Product…}
Labels :
DynamicType :
DynamicProperty :
LicenseKey : AAAAA-BBBBB-CCCCC-DDDDD-EEEEE
EditionKey : esx.enterprisePlus.cpuPackage
Name : VMware vSphere 6 Enterprise Plus
Total : 64
Used : 4
CostUnit : cpuPackage
Properties : {LicenseInfo, ProductName, Product…}
Labels :
DynamicType :
DynamicProperty :
LicenseKey : AAAAA-BBBBB-CCCCC-DDDDD-EEEEE
EditionKey : esx.vsomEnterprisePlus.cpuPackage
Name : VMware vSphere with Operations Man…}
Total : 64
Used : 0
CostUnit : cpuPackage
Properties : {LicenseInfo, ProductName, Product…}
Labels :
DynamicType :
DynamicProperty :
LicenseKey : AAAAA-BBBBB-CCCCC-DDDDD-EEEEE
EditionKey : esx.vcloudEnt.vram
Name : VMware vCloud Suite Enterprise
Total : 64
Used : 2
CostUnit : cpuPackage
Properties : {LicenseInfo, LicenseInfo, Suite…}
Labels :
DynamicType :
DynamicProperty :
Once you have a list of the keys, you can use that information to license the ESX hosts attached to the vCenter Server. Listing 1-17 shows how you set the license key for a specific host. Once the license key is set, it will return the server and license key that were specified.
Listing 1-17: Adding a license key to a host
function Set-LicenseKey {
<#
.SYNOPSIS
Sets a License Key for a host
.DESCRIPTION
This function will set a license key for a host
which is attached to a vCenter Server
.NOTES
Source: Automating vSphere Administration
.PARAMETER LicKey
The License Key
.PARAMETER VMHost
The vSphere host to add the license key to
.PARAMETER Name
The friendly name to give the license key
.EXAMPLE
Set-LicenseKey -LicKey "AAAAA-BBBBB-CCCCC-DDDDD-EEEEE" `
-VMHost "esxhost01.contoso.com" `
-Name $null
#>
param(
[String]$VMHost,
[String]$LicKey,
[String]$Name
)
Process {
$vmhostId = (Get-VMHost $VMHost | Get-View –Property `
Config.Host).Config.Host.Value
$servInst = Get-View ServiceInstance
$licMgr = Get-View $servInst.Content.licenseManager
$licAssignMgr = Get-View $licMgr.licenseAssignmentManager
$license = New-Object VMware.Vim.LicenseManagerLicenseInfo
$license.LicenseKey = $LicKey
$licAssignMgr.UpdateAssignedLicense(`
$VMHostId, $license.LicenseKey, $Name)
$hostlicense = (get-vmhost $VMhost).LicenseKey
Write-Host ("Host [$VMhost] license has been set to $hostlicense")
}
}
Set-LicenseKey -LicKey "AAAAA-BBBBB-CCCCC-DDDDD-EEEEE" `
-VMHost "esxhost01.contoso.com" `
-Name $null