Chapter 8. A Practical Example: Enforcing Anti-Affinity Rules
We can use the techniques that we’ve learned so far to write an automation script to solve a realistic task.
Task
Write an Automate method that enforces anti-affinity rules for virtual machines, based on a server_role
tag applied to each VM. There should be only one VM of any server_role
type running on any host in the cluster.
The Automate method should be run from a button visible on the VM details page. If another VM with the same server_role
tag is found running on the same host (hypervisor) as the displayed VM, then we live-migrate the current VM to another host with no other such tagged VMs. We also email all users in the EvmGroup-administrator
group to notify them that the migration occurred.
Solution
We can achieve the task in the following way (the entire script is also available on GitHub). We’ll define two methods internally within our Ruby script, relocate_vm
and send_email
. Our main code will be a simple iteration loop.
relocate_vm
The first method, relocate_vm
, makes use of a virtual column (vm.host_name
), and several associations to find a suitable host (hypervisor) to migrate the virtual machine to. These associations are vm.ems_cluster
to find the cluster that our VM is running on, ems_cluster.hosts
to find the other hypervisors in the cluster, and host.vms
to get the list of VMs running on a hypervisor. Finally, it calls a method (vm.migrate
) to perform the VM migration.
def
relocate_vm
(
vm
)
#
Get Mastering CloudForms Automation now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.