GitHub Actions - Loop over a list of items
by
Jeremy Canfield |
Updated: June 01 2025
| GitHub Actions articles
GitHub Actions can be used to do something whenever something happens in one of your GitHub repositories. If you are not familiar with GitHub Actions, check out my article Getting Started with GitHub Actions.
strategy matrix can be used to loop over a list of items. In this example, main-job will run three times, the first time echo apple, and second time echo banana, the third time echo watermelon.
name: my workflow
run-name: ${{ github.workflow }} run by ${{ github.actor }}
on:
workflow_dispatch:
jobs:
main-job:
runs-on: [self-hosted, linux]
strategy:
matrix:
fruits: ['apple', 'banana', 'watermelon']
steps:
- run: echo "${{ matrix.fruits }}"
For more complex scenarios, you may need to define JSON that contains the items you want to loop.
name: my workflow
run-name: ${{ github.workflow }} run by ${{ github.actor }}
on:
workflow_dispatch:
jobs:
job1:
runs-on: ubuntu-latest
outputs:
food: ${{ steps.xfood.outputs.food }}
steps:
- name: define food as a JSON list
id: xfood
run: echo "food={'include':[{'fruit':'apple','veggy':'pepper'}]}" >> $GITHUB_OUTPUT
job2:
runs-on: ubuntu-latest
needs: job1
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.job1.outputs.food) }}
steps:
# This should return: {fruit: apple, veggy: pepper}
- name: full JSON
run: echo "${{ toJSON(matrix) }}"
# This should return apple
- name: matrix.fruit
run: echo "${{ toJSON(matrix.fruit) }}"
# This should return pepper
- name: matrix.veggy
run: echo "${{ toJSON(matrix.veggy) }}"
Did you find this article helpful?
If so, consider buying me a coffee over at 