BacklogZero®

Ansible in a Minute · Ansible Core ·

Use query to get lookup results as a list

Short answer

Use query (or q) when a lookup must return a list you can loop over.

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

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: Print each inventory hostname from query
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Print hostname
      ansible.builtin.debug:
        msg: "{{ item }}"
      loop: "{{ query('ansible.builtin.inventory_hostnames', 'all') }}"

How it works

query always returns a list. lookup returns a comma-joined string by default. Use query when the next keyword is loop.

When to use it

  • Looping over files from fileglob
  • Looping over inventory hostnames from a lookup

Requirements

  • Ansible: >=2.14

Validation

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

Notes

q is an alias for query. Prefer the FQCN plugin name inside query. Do not use lookup when you need one list item per result.

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 to get lookup results as a list · Level Up Labs