Sara James
Sara James

Reputation: 143

How to loop over inventory_hostname in Ansible

I'm trying to add all the hosts of the dynamic inventory to the group: reachable.

Here is my playbook.

$ cat collect_try.yaml 
  ---
    - hosts: "{{ env }}:&{{ zone }}"
      become: true
      tasks:
        - add_host:
          name: "{{ inventory_hostname }}"
          group: reachable

    - name: dynamicgroup
      hosts: reachable
      gather_facts: false
      tasks:
        - debug: msg="{{ inventory_hostname }} is reachable"

Here is my output:

TASK [Gathering Facts] 
ok: [vm1.nodekite.com]
ok: [vm2.nodekite.com]
ok: [vm3.nodekite.com]
ok: [vm4.nodekite.com]

TASK [add_host] 
changed: [vm1.nodekite.com] => {
"add_host": {
    "groups": [
        "reachable"
    ],
    "host_name": "vm1.nodekite.com",
    "host_vars": {
        "group": "reachable"
    }
},
"changed": true
}
PLAY [dynamicgroup] 
META: ran handlers

TASK [debug] 
ok: [vm1.nodekite.com] => {
    "msg": "vm1.nodekite.com is reachable"
 
PLAY RECAP:
vm1.nodekite.com     : ok=3    changed=1    unreachable=0   <=====     
vm2.nodekite.com     : ok=1    changed=0    unreachable=0         
vm3.nodekite.com     : ok=1    changed=0    unreachable=0
vm4.nodekite.com     : ok=1    changed=0    unreachable=0

How to use loops to add all the hosts to the "group": "reachable". could someone please assist.

Upvotes: 1

Views: 1781

Answers (1)

Zeitounator
Zeitounator

Reputation: 44605

From add_host documentation notes:

This module bypasses the play host loop and only runs once for all the hosts in the play, if you need it to iterate use a with-loop construct.

In your specific case (i.e. dynamic host pattern in your play), you should be able to achieve your requirements using the inventory_hostnames lookup, e.g (not fully tested):

- name: Collect reachable hosts
  hosts: localhost
  gather_facts: false
  
  tasks:
    - name: Push hosts to "reachable" group
      vars:
        pattern: "{{ env }}:&{{ zone }}"
      add_host:
        name: "{{ item }}"
        group: reachable
      loop: "{{ query('inventory_hostnames', pattern) }}"

Upvotes: 2

Related Questions