0

I am trying to loop over my hosts from my inventory in Ansible, and use the name of the host of that iteration in a command. In particular, I am trying to set the hostname of each of my hosts to whatever I have called them in my hosts file. So, I have web01, web02, web03 etc for my webservers -- I want to set these as hostnames on the servers in each question, i.e. I want to loop over "all" hosts and when I'm on web01 (first iteration), I want to pass that name of the host I am on to the hostname module. This is what I tried:

- hosts: all
become: true
tasks:
  - hostname:
      name: "{{ item }}"
    with_items: "{{ play_hosts }}"

However, instead of setting as hostname the name of the host I am on, this tries to set every single host from my ansible config as hostname on each single server. So it tries to do:

connect to web01; hostname -> web01; hostname -> web02; hostname -> web03
connect to web02; hostname -> web01; hostname -> web02; hostname -> web03
connect to web03; hostname -> web01; hostname -> web02; hostname -> web03

Instead I want:

connect to web01; hostname -> web01
connect to web02; hostname -> web02
connect to web03; hostname -> web03

How can I do that?

I found a similar question here: Ansible: setting hostname over inventory

but this was answered with a more complicated solution than I am hoping for. The suggestion there was to add suffixes, but surely a simple loop like I want shouldn't require that in principle.

4

You don't need to loop over hosts, as this is one of the most fundamental Ansible functions (it is disabled on a few selected modules, but hostname is not one of them).

To set the target machine's hostname to the value defined in the Ansible inventory file, all you need to do, is to reference the inventory_hostname variable (see Magic Variables):

- hosts: all
  become: true
  tasks:
    - hostname:
        name: "{{ inventory_hostname }}"
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.