Ansible in a Minute · Ansible Core ·
Use index_var to track loop position
Short answer
Set loop_control index_var so each iteration exposes a 0-based index you can print or pass to a task.
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 apple banana pear and print each fruit with its 0-based index using index_var my_idx
Example
A quick heads-up: Every environment is different. Review and test this example before you run it on systems you care about.
---
# Prompt: loop apple banana pear and print each fruit with its 0-based index using index_var my_idx
- name: Count our fruit
hosts: all
gather_facts: false
tasks:
- name: Count our fruit
ansible.builtin.debug:
msg: "{{ item }} with index {{ my_idx }}"
loop:
- apple
- banana
- pear
loop_control:
index_var: my_idxHow it works
index_var stores the current loop index in a name you choose. The first item is 0. This task prints apple with index 0, then banana with index 1, then pear with index 2.
When to use it
- Numbering items in a recap
- Passing a 0-based offset into a module argument
Requirements
- Ansible: >=2.14
Validation
- Syntax validated
- Not execution-tested
- Last verified 2026-10-02
Notes
index_var is 0-indexed. loop.index from Jinja is 1-indexed. Prefer index_var when you need the index in the task, not only in a template.
Reference
- Tracking progress through a loop with index_var (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.