Linux – Change remote server’s hostname with ansible

ansiblehostnamelinuxUbuntu

I want to change my remote server's hostname so I used the hostname module:

- hostname: name="{{my_hostname}}"

But that also changed the ansible_host to that value, and so messed up remaining tasks.

When I did it manually:

- shell: hostnamectl set-hostname {{my_hostname}}

Then the remote server's hostname was changed, AND the ansible_host global var wasn't changed, and all remaining plays completed successfully.

Am I using the hostname module correctly? I have a feeling it doesn't do what I think.

(I also noticed lots of bug reports in the repo, but I'm not sure if they're related to what I'm doing as I'm not using cloud-init).

Best Answer

You should know the difference between inventory_hostname (how you call it) and ansible_host (how you reach it). You could use the ip-address as ansible_host in your inventory entry:

   my_hostname ansible_host=192.168.12.34

Then use the hostname module to change the hostname of the machine to "{{ inventory_hostname }}".