Home > OS >  Loop through JSON file and set each value as a variable within Github Actions workflow
Loop through JSON file and set each value as a variable within Github Actions workflow

Time:03-23

Goal: set ~20 variables that are stored in a JSON file into the $GITHUBENV during GHA job.

Currently, I am hardcoding this with the parsing of the JSON file with jq:

- name: Set env variables from variables json
      run: |
          echo "NAME=$(jq -r '.name' variables.json)" >> $GITHUB_ENV
          echo "AGE=$(jq -r '.age' variables.json)" >> $GITHUB_ENV
          echo "WEIGHT=$(jq -r '.weight' variables.json)" >> $GITHUB_ENV
          ...etc

How can I "for loop" through this process?

Afterwards, I want to check if the variables entered manually through a workflow_dispatch run of the job match what are in the variables.json file. If they don't match, I want to update the json file with the new manually entered value:

- name: Set age if dispatching
      shell: bash -l {0}
      if: github.event.inputs.age != env.AGE
      run: echo "$( jq '.name = ${{github.event.inputs.age}}' variables.json )" > variables.json

Similarly, how do I loop through this process?

CodePudding user response:

I suggest you to use the JSON to variables GitHub Actions. From the doc:

test.json

{
    "value": "value",
    "array": [
        {
            "value": "value 0"
        },
        "value 1"
    ],
    "obj": {
        "value1": "value1",
        "value2": "value2"
    }
}

workflow.main

- name: JSON to variables
  uses: antifree/[email protected]
  with:
    filename: 'test.json'
    prefix: test
- name: Show output
  run: echo "The time was ${{ env.test_value }}, ${{ env.test_array_0_value }}, ${{ env.test_obj_value1 }}"

  • Related