Table of Contents

VM Affinity Rules

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:

  1. Check validity of service request
  2. Create groups if required
  3. Create affinity rule
  4. Update documentation

Check validity of 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.

Create Groups If Required

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:

Create Affinity Rule

To create the actual affinity rule follow these steps:

Update Documentation

Because DRS rules can get lost when DRS gets disabled you should document the rules very precise. Luckily there are export and import scrips:

Export Script

$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
}

Import Script

$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)]))
}

Useful Links

The scripts are originally created by LucD