0
votes

Below is how my inventory hosts file looks like.

[all_hosts]
server1 USER=user1
server3 USER=user2
server5 USER=user1
…..

In my ansible playbook I wish to always refer to the first host i.e server1 and USER=user1 for a copy task because the file to be copied always resides on the first host in the inventory_hostname. Consider -e domain_home=all_hosts

---

- name: "Play 1"

  hosts: "{{ domain_home }}"
  gather_facts: false
  vars:
    ansible_ssh_extra_args: -o StrictHostKeyChecking=no
  tasks:

    - debug:
        msg: "Although the inventory hostname is {{ inventory_hostname }} the first host will always be  <need help get first host> and the user will always be <need help get user for first host>

   

Can you please suggest ?

1

1 Answers

1
votes

The groups["all_hosts"] fact is ordered by their position in the .ini file, so you can just ask for the [0]th item (or use the | first filter), and then the hostvars dict is similarly indexed by their names

- debug:
    msg: >-
     Although the inventory hostname is {{ inventory_hostname }}
     the first host will always be {{ host0 }}
     and the user will always be {{ hostvars[host0].USER }}
  vars:
    host0: '{{ groups[domain_home][0] }}'

In the future, to help teach yourself to fish, - debug: var=vars and - debug: var=hostvars is illustrative to see what information is available to you at any point in the playbook