For any familiar with PowerCLI, this is one of the first scripts someone may learn. It is just long enough to need more than one-liner, but short enough to feel like you don’t need to be an expert. Here is one I posted on this site over a decade ago:
param([string]$servers)
$spec= new-object vmware.vim.virtualmachineconfigspec
$spec.tools=new-object vmware.vim.toolsconfiginfo
$spec.tools.toolsupgradepolicy ="upgradeatpowercycle"
$vms= get-vm $servers
Foreach($vm in $vms){
$view=$vm|get-view
$view.reconfigvm($spec)
}
I share this so we have a baseline when looking at the Ansible version.
---
- name: Update VMTools Upgrade Policy
hosts: vcenters
gather_facts: no
collections:
- vmware.vmware_rest
tasks:
- name: Get all VMs
vmware.vmware_rest.vcenter_vm_info:
vcenter_hostname: "{{ inventory_hostname }}"
vcenter_username: "{{ vcenter_username }}"
vcenter_password: "{{ vcenter_passwords[inventory_hostname] }}"
vcenter_validate_certs: no
delegate_to: localhost
register: vms
- name: Change VMTools upgrade policy to UPGRADE_AT_POWER_CYCLE
vmware.vmware_rest.vcenter_vm_tools:
vcenter_hostname: "{{ inventory_hostname }}"
vcenter_username: "{{ vcenter_username }}"
vcenter_password: "{{ vcenter_passwords[inventory_hostname] }}"
vcenter_validate_certs: no
vm: "{{ item.vm }}"
upgrade_policy: UPGRADE_AT_POWER_CYCLE
register: _result
delegate_to: localhost
loop:
"{{vms.value}}"
The two tasks here are straightforward even though they look and feel a more complicated than the PowerCLI version.
The first tasks gathers all the VMs in vCenter, and the second tasks changes the VMtools upgrade policy so VMtools upgrades during a reboot. That’s it.
Ansible’s benefit over PowerCLi is it can allow non-technical user to run pre-written playbooks very easily with little knowledge needed. Would I suggest everyone start transcribing all the Powershell/PowerCLI scripts to Ansible? Definitely not! But I do think exercises like this are important for learning Ansible or anything new as when we take a process or a script with which we are already familiar, it makes understanding the new tool or process that much easier.
Enjoy