4

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).

lonix
  • 896
  • 10
  • 23
  • 2
    Are you using some kind of dynamic inventory? And where are you using `ansible_host`? – Michael Hampton Sep 02 '19 at 18:03
  • 1
    @MichaelHampton I thought `ansible_host` comes from the hosts inventory file, as one of those built-in variables? Regardless, is the code above supposed to work, or did I use the wrong module? – lonix Sep 02 '19 at 18:49
  • 1
    `ansible_host` comes from the host's own hostname. It can be wrong, which is presumably why you are changing it! The inventory hostname is stored in `inventory_hostname`. Most of the time, `inventory_hostname` is what you want to use in your own playbooks to refer to your hosts. – Michael Hampton Sep 02 '19 at 18:51
  • 1
    @MichaelHampton Thanks for the clarification! Does the `hostname` module do what I think it does - change the hostname of the remote server? – lonix Sep 03 '19 at 07:40
  • Yes, that's exactly what it is documented to do. – Michael Hampton Sep 03 '19 at 07:41
  • 1
    @Ionix - it's a fine distinction, but `hostname:` module changes the *target* host's hostname. It doesn't have to be remote, it can be used on the local system (ansible controller) as well. – Jeter-work Mar 28 '21 at 23:06

1 Answers1

1

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 }}".

bbaassssiiee
  • 160
  • 6