BacklogZero®

Ansible in a Minute · Ansible Core ·

Use query in loop instead of lookup

Short answer

Use query with loop so lookup plugin results are a list. lookup returns a comma-joined string by default.

Subscribe for updates

Get an email whenever we publish new guides and blog posts. Unsubscribe anytime.

By subscribing you agree we may email you about Ansible in a Minute and related Level Up Labs updates. We store your address in the same lead sheet as our contact form.

Request

loop query ansible.builtin.inventory_hostnames all and print each host

Example

A quick heads-up: Every environment is different. Review and test this example before you run it on systems you care about.

YAML
---
- name: Loop inventory hostnames from query
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Print each inventory hostname
      ansible.builtin.debug:
        msg: "{{ item }}"
      loop: "{{ query('ansible.builtin.inventory_hostnames', 'all') }}"

How it works

loop requires a list. lookup returns a comma-separated string unless you set wantlist=True. query always returns a list, so it is the input loop expects.

When to use it

  • Looping inventory hostnames from a lookup plugin
  • Looping fileglob or other lookup results without splitting a string

Requirements

  • Ansible: >=2.14

Validation

  • Syntax validated
  • Not execution-tested
  • Last verified 2026-09-17

Notes

These two expressions do the same work: query('ansible.builtin.inventory_hostnames', 'all') and lookup('ansible.builtin.inventory_hostnames', 'all', wantlist=True). Prefer query with loop. q is an alias for query.

Reference

Built for every Ansible use case in every organization

BacklogZero can generate this kind of automation in your environment, just like it did here.

Get BacklogZero today

Related guides

Back to Ansible in a Minute

Use query in loop instead of lookup · Level Up Labs