LUKER
LUKER

Reputation: 536

Iterate through JSON Objects from JSON File

I'm trying to iterate through an array of objects from a JSON file, but am unable to. I'm currently getting this error:

Error when evaluating 'strategy' for job 'create'. .github/workflows/rolling-deployment.yml (Line: 66, Col: 15): A sequence was not expected

Here's the current workflow file:

name: Rolling Deploy

on:
  push:
    branches: [ "main" ]

jobs:
  servers:
    runs-on: ubuntu-latest
    outputs:
      matrix: ${{ steps.read-json.outputs.matrix }}
    environment: Staging
    steps:
      ... a few other steps in here to create the json file
      - name: Read JSON
        id: read-json
        run: |
          JSON=$(cat ./neededServers.json)
          echo "matrix=${JSON//'%'/'%25'}" >> $GITHUB_OUTPUT
    
  create:
    needs: servers
    runs-on: ubuntu-latest
    strategy:
      matrix: ${{ fromJson(needs.servers.outputs.matrix) }}
    steps:
      - name: Test
        run: echo "${{matrix.reference}}"

I've run echo ${{needs.servers.outputs.matrix}} in the create without the strategy, and it prints the JSON file. Here's an example JSON file too:

[
    {
        "config":"small",
        "ID":"1234",
        "memory":"4096",
        "vcpus":"2"
    },{
        "config":"small",
        "ID":"2345",
        "memory":"4096",
        "vcpus":"2"
    }
]

I'm not sure if I'm doing something wrong or if it isn't possible.

Upvotes: 1

Views: 653

Answers (1)

LUKER
LUKER

Reputation: 536

JSON should contain the "include" key for the array:

{
    "include": [
        {
            "config":"small",
            "ID":"1234",
            "memory":"4096",
            "vcpus":"2"
        },
        {
            "config":"small",
            "ID":"1234",
            "memory":"4096",
            "vcpus":"2"
        }
    ]
}

Upvotes: 1

Related Questions