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.
---
- name: Loop through all inventory hostnames
hosts: all
gather_facts: true
tasks:
- name: Loop through all inventory hostnames
ansible.builtin.debug:
msg: "Hostname: {{ inventory_hostname }}"How it works
This play runs on every host and prints inventory_hostname. Use query when you need a list from a lookup instead of relying on the play host loop. 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-16
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
- The query/q function (Ansible docs)
Built for every Ansible use case in every organization
BacklogZero can generate this kind of automation in your environment, just like it did here.