While deploying new VM’s is easy with Ansible, I kept on struggling with setting the hostname. There is Ansible documentation to use vmware_vm_shell
module to set the hostname. The following is stated on their help page.
- name: Change hostname of guest machine vmware_vm_shell: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no datacenter: "{{ datacenter }}" folder: "/{{datacenter}}/vm" vm_id: "{{ vm_name }}" vm_username: testUser vm_password: SuperSecretPassword vm_shell: "/usr/bin/hostnamectl" vm_shell_args: "set-hostname new_hostname > /tmp/$$.txt 2>&1" delegate_to: localhost
Whatever I tried, I could not manage to get it working. It dit not error but just didn’t work.
After a couple of hours this is my workaround:
- name: Change hostname of guest machine vmware_vm_shell: hostname: "{{ vcenter_hostname }}" username: "{{ vcenter_username }}" password: "{{ vcenter_password }}" validate_certs: no datacenter: "{{ datacenter }}" folder: "/{{datacenter}}/vm" vm_id: "{{ vm_name }}" vm_username: testUser vm_password: SuperSecretPassword vm_shell: "/usr/bin/bash" vm_shell_args: " -c \" {{item}} \" " with_items: - echo {{ vm_name }} > /etc/hostname - hostname {{ vm_name }} delegate_to: localhost
Now it will set the hostname the same as the vm name.

It’s probably not perfect. Let me know if you have a better solution.
Have fun!