Skip to main content

Iterate over a list with for_each

This guide shows how to use the for_each control task to repeat a block of tasks for each item in a list.

Basic for_each task​

Add a for_each key to a task entry to make it a for_each task:

name: For each example
compute_type: cpu-4
blocks:
main:
tasks:
list_files:
name: List files
uses: my-account/list-[email protected]
process_each:
name: Process each
start_on:
- list_files
for_each:
items: ${{tasks.list_files.outputs.files}}
block: per_file_block

per_file_block:
tasks:
transform:
name: Transform
uses: my-account/transform-[email protected]
args:
file: ${{tasks.process_each.for_each.item}}
step: ${{tasks.process_each.for_each.index}}

list_files runs first and produces an array in its files output. process_each then iterates over that array, running per_file_block once for each element.

Inside per_file_block, ${{tasks.process_each.for_each.item}} is the current element and ${{tasks.process_each.for_each.index}} its zero-based position; see For Each loop variables.

Iterate over a run input​

If your run input is already a JSON array, you can iterate over it directly. This version keeps per_file_block from the example above:

inputs:
file_list: {}

blocks:
main:
tasks:
process_each:
name: Process each
for_each:
items: ${{inputs.file_list}}
block: per_file_block

Pass the input as a JSON array when starting the run:

swale workflow run start \
--project-name my-project \
--workflow-id <workflow-id> \
--input 'file_list=["file1.csv","file2.csv","file3.csv"]'

Inspect each iteration​

After starting a run, open it and expand the for_each task's node in its Workflow Graph: it shows one group per iteration, labelled with its item. Click a task inside a group to open that iteration's task. UI representation describes the node.

Next steps​