DOC_INDEX
THEME
DOCS/Learn OrchStep/Loops

Loops

Iterate over lists, counts and ranges, with per-iteration outputs

Any step can loop. The shorthand covers most cases:

name: loops-demo
defaults:
  servers:
    - "web1.example.com"
    - "web2.example.com"
    - "web3.example.com"

tasks:
  main:
    steps:
      - name: ping_all
        loop: "{{ vars.servers }}"      # items from a variable
        func: shell
        do: echo "checking {{ loop.item }} ({{ loop.index1 }}/{{ loop.length }})"

      - name: three_times
        loop: 3                          # plain count
        func: shell
        do: echo "round {{ loop.item }}"

The loop context

Inside a looping step these are available (all verified):

VariableMeaning
loop.itemcurrent item (or loop.<name> with as:)
loop.index0-based index
loop.index11-based index
loop.first / loop.lastboolean edge markers
loop.lengthtotal iterations

Full form: items, range, as

- name: rollout
  loop:
    items: "{{ vars.servers }}"
    as: hostname                   # loop.hostname instead of loop.item
  func: shell
  do: echo "deploying to {{ loop.hostname }}"

- name: ports
  loop:
    range: [8080, 8082]            # inclusive
    as: port
  func: shell
  do: echo "port {{ loop.port }}"

Outputs become arrays

A looping step's outputs: collect one entry per iteration:

- name: gather
  loop: "{{ vars.servers }}"
  func: shell
  do: echo "{{ loop.item }}"
  outputs:
    host: "{{ loop.item }}"

- name: verify
  func: assert
  args:
    conditions:
      - condition: '{{ eq (len steps.gather.outputs) 3 }}'
      - condition: '{{ eq (index steps.gather.outputs 1).host "web2.example.com" }}'

Both Go-template (index steps.gather.outputs 1) and JavaScript (steps.gather.outputs[1].host) access work.

Run it

orchstep run

Where to go next

Error Handling - retries, recovery and cleanup.