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

6
  • 2
    Are you using some kind of dynamic inventory? And where are you using ansible_host? Commented Sep 2, 2019 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? Commented Sep 2, 2019 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. Commented Sep 2, 2019 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? Commented Sep 3, 2019 at 7:40
  • 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. Commented Mar 28, 2021 at 23:06

1 Answer 1

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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.