-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Balance-VMs.ps1
330 lines (261 loc) · 11.1 KB
/
Balance-VMs.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
<#
.SYNOPSIS
Balances VMs across hosts in a vCenter cluster, ensuring no host exceeds the specified VM limit.
.DESCRIPTION
This script connects to a vCenter server using encrypted credentials, identifies overloaded hosts within a specified cluster,
and migrates VMs to underloaded hosts to maintain a balanced distribution. It excludes specified VMs from migration
based on their names or assigned tags. Additionally, it includes an enhanced dry-run mode to simulate migrations safely.
.AUTHOR
virtualox
.GITHUB_REPOSITORY
https://github.com/virtualox/VM-Balancer
.LICENSE
This script is licensed under the GPL-3.0 License. See the LICENSE file for more information.
.USAGE
.\Balance-VMs.ps1 [-DryRun]
.PARAMETER DryRun
Executes the script in simulation mode without performing actual migrations. Useful for testing and verifying actions.
.NOTES
- Ensure that the encryption key and encrypted credentials have been set up using Generate-EncryptionKey.ps1 and Create-VCenterCredentials.ps1.
- Adjust the configuration variables and exclusion criteria within the script as needed.
- The script requires appropriate permissions to migrate VMs within the specified vCenter cluster.
#>
param (
[switch]$DryRun
)
# === Configuration Variables ===
# Path to the encryption key file
$encryptionKeyPath = "C:\Secure\Credentials\encryptionKey.key" # <-- Must match the key generated by Generate-EncryptionKey.ps1
# Path to the encrypted credentials file
$credentialPath = "C:\Secure\Credentials\vcCredentials.xml" # <-- Must match the credential path used in Create-VCenterCredentials.ps1
# vCenter Server details
$vcServer = "your_vcenter_server" # <-- Replace with your vCenter server name or IP
$clusterName = "YourClusterName" # <-- Replace with your cluster name
# VM balancing settings
$maxVMsPerHost = 60 # Maximum number of VMs per host
# Exclusion Settings
## Name-Based Exclusion
# Specify exact VM names or use wildcards for patterns
$excludeVMNames = @(
"cp-replica-*", # Exclude VMs with names starting with 'cp-replica-'
"horizon-*", # Exclude VMs managed by Horizon (assuming they start with 'horizon-')
"*-replica*", # Exclude any VM containing '-replica' in its name
"Important-VM1", # Exclude specific VM by exact name
"Critical-VM2" # Add more as needed
)
## Tag-Based Exclusion
# Specify the names of tags assigned to VMs that should be excluded
$excludeVMTags = @(
"DoNotMigrate",
"Infrastructure",
"VDI"
)
# === End of Configuration Variables ===
# Import the PowerCLI module
Import-Module VMware.PowerCLI -ErrorAction Stop
# Suppress certificate warnings (optional, remove if not needed)
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false
# Function to check if the encryption key exists
function Test-EncryptionKeyExists {
param (
[string]$Path
)
return (Test-Path -Path $Path)
}
# Function to check if the credentials file exists
function Test-CredentialsFileExists {
param (
[string]$Path
)
return (Test-Path -Path $Path)
}
# Function to retrieve credentials
function Get-Credentials {
param (
[string]$KeyPath,
[string]$CredPath
)
try {
# Read the encryption key
$key = Get-Content -Path $KeyPath -Encoding Byte
# Read the encrypted credentials JSON
$credentialJson = Get-Content -Path $CredPath -Raw | ConvertFrom-Json
$username = $credentialJson.Username
$encryptedPassword = $credentialJson.EncryptedPassword
# Decrypt the password
$securePassword = $encryptedPassword | ConvertTo-SecureString -Key $key
# Create PSCredential object
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $securePassword
return $cred
}
catch {
Write-Error "Failed to retrieve and decrypt credentials: $_"
exit 1
}
}
# Function to check if the host is eligible (connected and not in maintenance mode)
function Is-HostEligible {
param (
$VMHost
)
return ($VMHost.ConnectionState -eq 'Connected' -and -not $VMHost.ExtensionData.Runtime.InMaintenanceMode)
}
# Function to apply exclusion filters to VMs
function Apply-ExclusionFilters {
param (
[VMware.VimAutomation.ViCore.Impl.V1.Inventory.VirtualMachineImpl]$VM
)
# Name-Based Exclusion
foreach ($pattern in $excludeVMNames) {
if ($VM.Name -like $pattern) {
return $false
}
}
# Tag-Based Exclusion
foreach ($tag in $excludeVMTags) {
if ($VM.Tags -contains $tag) {
return $false
}
}
return $true
}
# Function to secure the script execution
function Verify-Security {
# Ensure encryption key exists
if (-not (Test-EncryptionKeyExists -Path $encryptionKeyPath)) {
Write-Error "Encryption key not found at '$encryptionKeyPath'. Please generate it using Generate-EncryptionKey.ps1 and store credentials using Create-VCenterCredentials.ps1."
exit 1
}
# Ensure credentials file exists
if (-not (Test-CredentialsFileExists -Path $credentialPath)) {
Write-Error "Encrypted credentials file not found at '$credentialPath'. Please store credentials using Create-VCenterCredentials.ps1."
exit 1
}
}
# Function to get host object by name
function Get-HostByName {
param (
[string]$Name
)
return $hosts | Where-Object { $_.Name -eq $Name }
}
# Main Execution
# Verify security prerequisites
Verify-Security
# Retrieve credentials
$cred = Get-Credentials -KeyPath $encryptionKeyPath -CredPath $credentialPath
# Connect to vCenter
try {
Connect-VIServer -Server $vcServer -Credential $cred -ErrorAction Stop
Write-Output "Successfully connected to vCenter Server '$vcServer'."
}
catch {
Write-Error "Failed to connect to vCenter Server '$vcServer'. $_"
exit 1
}
# Get the cluster object
$cluster = Get-Cluster -Name $clusterName -ErrorAction SilentlyContinue
if (-not $cluster) {
Write-Error "Cluster '$clusterName' not found."
Disconnect-VIServer -Server $vcServer -Confirm:$false
exit 1
}
# Get all eligible hosts in the cluster
$hosts = Get-VMHost -Location $cluster | Where-Object { Is-HostEligible -VMHost $_ }
if ($hosts.Count -eq 0) {
Write-Error "No eligible hosts found in cluster '$clusterName'. Ensure that hosts are not in Maintenance or Disconnected states."
Disconnect-VIServer -Server $vcServer -Confirm:$false
exit 1
}
# Create a hashtable to store host VM counts
$hostVMCounts = @{}
foreach ($vmHost in $hosts) {
# Retrieve all VMs on the host
$vmsOnHost = Get-VM -Location $vmHost -ErrorAction SilentlyContinue
# Apply Exclusion Filters
$vmsToConsider = $vmsOnHost | Where-Object { Apply-ExclusionFilters -VM $_ }
# Count the number of VMs to consider for migration
$vmCount = $vmsToConsider.Count
$hostVMCounts[$vmHost.Name] = $vmCount
}
# Identify overloaded and underloaded hosts
$overloadedHosts = $hostVMCounts.GetEnumerator() | Where-Object { $_.Value -gt $maxVMsPerHost } | Sort-Object -Property Value -Descending
$underloadedHosts = $hostVMCounts.GetEnumerator() | Where-Object { $_.Value -lt $maxVMsPerHost } | Sort-Object -Property Value
if ($overloadedHosts.Count -eq 0) {
Write-Output "All hosts have $maxVMsPerHost VMs or fewer. No balancing needed."
Disconnect-VIServer -Server $vcServer -Confirm:$false
exit 0
}
if ($underloadedHosts.Count -eq 0) {
Write-Output "No hosts available with less than $maxVMsPerHost VMs to migrate VMs to."
Disconnect-VIServer -Server $vcServer -Confirm:$false
exit 0
}
# Start balancing
foreach ($overloaded in $overloadedHosts) {
$overHostName = $overloaded.Key
$overHostVMCount = $overloaded.Value
$overHost = Get-HostByName -Name $overHostName
$vmsToMoveCount = $overHostVMCount - $maxVMsPerHost
if ($vmsToMoveCount -le 0) {
continue
}
Write-Output "Host '$overHostName' is overloaded with $overHostVMCount VMs. Need to move $vmsToMoveCount VMs."
# Get VMs on the overloaded host, excluding replicas and tagged VMs, sorted by power state (optional: adjust sorting as needed)
$vmsOnOverHost = Get-VM -Location $overHost | Where-Object { Apply-ExclusionFilters -VM $_ } | Sort-Object -Property PowerState
foreach ($vm in $vmsOnOverHost) {
# Check again if there are still VMs to move
if ($vmsToMoveCount -le 0) {
break
}
# Find a target host that is underloaded and can host the VM
$targetHostEntry = $underloadedHosts | Where-Object { $_.Value -lt $maxVMsPerHost } | Sort-Object -Property Value | Select-Object -First 1
if ($targetHostEntry) {
$targetHostName = $targetHostEntry.Key
$targetHostObj = Get-HostByName -Name $targetHostName
# Additional check to ensure the target host is still eligible
if ($targetHostObj.ConnectionState -ne 'Connected' -or $targetHostObj.ExtensionData.Runtime.InMaintenanceMode) {
Write-Warning "Target host '$targetHostName' is no longer eligible. Skipping."
# Remove the host from underloaded list
$underloadedHosts = $underloadedHosts | Where-Object { $_.Key -ne $targetHostName }
continue
}
if ($DryRun) {
Write-Output "[Dry-Run] Would migrate VM '$($vm.Name)' from '$overHostName'."
# Simulate the migration by updating the VM counts
$hostVMCounts[$overHostName] -= 1
$hostVMCounts[$targetHostName] += 1
# Update the underloaded hosts list if the target host reaches the limit
if ($hostVMCounts[$targetHostName] -ge $maxVMsPerHost) {
$underloadedHosts = $underloadedHosts | Where-Object { $_.Key -ne $targetHostName }
}
$vmsToMoveCount -= 1
}
else {
Write-Output "Migrating VM '$($vm.Name)' from '$overHostName' to '$targetHostName'. (Hardware Version: $($vm.HardwareVersion))"
try {
# Perform the migration
Move-VM -VM $vm -Destination $targetHostObj -ErrorAction Stop
# Update the VM counts
$hostVMCounts[$overHostName] -= 1
$hostVMCounts[$targetHostName] += 1
# Update the underloaded hosts list if the target host reaches the limit
if ($hostVMCounts[$targetHostName] -ge $maxVMsPerHost) {
$underloadedHosts = $underloadedHosts | Where-Object { $_.Key -ne $targetHostName }
}
$vmsToMoveCount -= 1
}
catch {
Write-Warning "Failed to migrate VM '$($vm.Name)': $_"
}
}
}
else {
Write-Warning "No available target hosts with less than $maxVMsPerHost VMs to migrate VM '$vm.Name'."
break
}
}
}
Write-Output "VM balancing complete."
# Disconnect from vCenter
Disconnect-VIServer -Server $vcServer -Confirm:$false