How do i loop over hosts identified by wildcards in Ansible

Viewed 476

Below is my playbook that works fine.

---
- hosts: "PROD_SERVERS"
  user: "{{USER}}"
  tasks:

       - name: Check if all hosts are reachable
         fail:
           msg: "Server is UNREACHABLE."
         when: "hostvars[item].ansible_facts|list|length == 0"
         with_items: "{{ groups.PROD_SERVERS }}"

However, can you help me with the syntax when the host is presented as wildcard i.e {{ENV}}_*?

---
- hosts: "{{ENV}}_*"
  user: "{{USER}}"
  tasks:

       - name: Check if all hosts are reachable
         fail:
           msg: "Server is UNREACHABLE."
         when: "hostvars[item].ansible_facts|list|length == 0"
         with_items: "{{ groups.{{ENV}}_* }}"   <------- Need help with this part of the code
1 Answers

There are special variables also called as "magic variables" to identify the hosts in the current play. They are:

  • ansible_play_hosts
  • ansible_play_batch

You can use one of these variables to loop with instead of the inventory group name.

Example with ansible_play_hosts:

    - fail:
        msg: "Server is UNREACHABLE."
      when: hostvars[item].ansible_facts|list|length == 0
      with_items: "{{ ansible_play_hosts }}"

Update:

Changed the example for Ansible version "2.4.x", the loop should be performed with with_items rather than loop. Quoting from official documentation

We added loop in Ansible 2.5. It is not yet a full replacement for with_<lookup>, but we recommend it for most use cases.

Note: For Ansible "2.9.16" and "2.10.2" loop works as well.

Related