user7431944
user7431944

Reputation: 9

add_host - divide by os

I want to create playbook that going on the entire inventory file and divide the servers to 2 groups: Windows and Linux (add-host going only on the first server on the inv)

I tried this code:

   - name: Linux Group
     add_host:
       name: "{{ item }}"
       group: LinuxGroup
     when:  hostvars[" {{ item }} "]['ansible_system']  == 'Linux'
     with_items: "{{ ansible_play_hosts_all }} "

PS:

I changed the code to this:

    tasks:
   - name: Create linux group
     add_host:
       name: "{{ item }}"
       group: LinuxGroup
     when: hostvars[item].ansible_system == 'Linux'
     with_items: "{{ ansible_play_hosts_all }} "
     ignore_errors: yes

   - name: ping to Linux
     ping:
     with_items: LinuxGroup

and when I run the code the windows servers are skipped in the "Create linux group" task, but I used the module debug to print to group's items and there are the windows servers.

Upvotes: 1

Views: 301

Answers (1)

franklinsijo
franklinsijo

Reputation: 18270

The fact ansible_system is a key under the host, not a list of keys. Also, conditional statements should not include jinja2 templating delimiters such as {{ }} or {% %}, use hostvars[item] instead of hostvars[ "{{ item }}" ].

Make sure gather_facts is set to true.

Note that the add_host module does not update the inventory file but updates the in-memory inventory. I have included a debug task to print the groups from the in-memory inventory of ansible.

  gather_facts: true
  tasks:
    - name: Linux Group
      add_host:
        name: "{{ item }}"
        group: LinuxGroup
      when:  hostvars[item].ansible_system == 'Linux'
      with_items: "{{ ansible_play_hosts_all }}"
    - debug: msg="{{ groups }}"

Upvotes: 1

Related Questions