Summary: Info and tips about VM Affinity rules on VMware, as well as scripts on how to export and import them.
Date: Around 2014
Refactor: 1 May 2025: Checked links and formatting.
If a service request regarding VM affinity is received you should follow this procedure to implement the service request:
VMs can only have a (anti-)affinity if they are part of the same cluster. So always check first if the VMs are in the same cluster. If not, deny the request, if they are, continue.
If the request if to host a VM onto specific hosts you first need to create groups, even if it's just one VM of just one host. VM-Host rules only work with groups.
To create a group follow these steps:
To create the actual affinity rule follow these steps:
Because DRS rules can get lost when DRS gets disabled you should document the rules very precise. Luckily there are export and import scrips:
$outfile = "C:\rules.txt" Remove-Item $outfile $clusterName = <cluster-name> $rules = get-cluster -Name $clusterName | Get-DrsRule foreach($rule in $rules){ $line = (Get-View -Id $rule.ClusterId).Name $line += ("," + $rule.Name + "," + $rule.Enabled + "," + $rule.KeepTogether) foreach($vmId in $rule.VMIds){ $line += ("," + (Get-View -Id $vmId).Name) } $line | Out-File -Append $outfile }
$file = "C:\rules.txt" $rules = Get-Content $file foreach($rule in $rules){ $ruleArr = $rule.Split(",") if($ruleArr[2] -eq "True"){$rEnabled = $true} else {$rEnabled = $false} if($ruleArr[3] -eq "True"){$rTogether = $true} else {$rTogether = $false} get-cluster $ruleArr[0] | ` New-DrsRule -Name $ruleArr[1] -Enabled $rEnabled -KeepTogether $rTogether -VM (Get-VM -Name ($ruleArr[4..($ruleArr.Count - 1)])) }
The scripts are originally created by LucD