Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read JSON file in Github Actions

I want to read a JSON file and use a property in a string in a Github Actions YAML file. How do I do this? (I want the version of the package.json)

like image 875
exoRift Avatar asked May 20 '20 17:05

exoRift


People also ask

Does GitHub actions have jq?

Run jq is not certified by GitHub.

What is GitHub actions documentation?

GitHub Actions Documentation Automate, customize, and execute your software development workflows right in your repository with GitHub Actions. You can discover, create, and share actions to perform any job you'd like, including CI/CD, and combine actions in a completely customized workflow.

How to call HTTPS endpoint from JSON file?

- run: call some https endpoint > at.json - run: echo "AUTH_TOKEN= $ (jq '.authorizationToken' at.json)" >> $GITHUB_ENV - run: echo "$ { { env.AUTH_TOKEN }}" Line 1: some command which calls some external service via HTTPS. Response payload is JSON. this json data is then stored straight away into a file called at.json.

How are secrets used in GitHub actions workflows?

The secrets that you create are available to use in GitHub Actions workflows. GitHub uses a libsodium sealed box to help ensure that secrets are encrypted before they reach GitHub and remain encrypted until you use them in a workflow.


Video Answer


2 Answers

Use the built-in fromJson(value) (see here: https://docs.github.com/en/actions/learn-github-actions/expressions#fromjson)

Reading a file depends on the shell you're using. Here's an example for sh:

name: Test linux job
on:
  push

jobs:
  testJob:
    name: Test
    runs-on: ubuntu-latest
    steps:
      - id: set_var
        run: |
          content=`cat ./path/to/package.json`
          # the following lines are only required for multi line json
          content="${content//'%'/'%25'}"
          content="${content//$'\n'/'%0A'}"
          content="${content//$'\r'/'%0D'}"
          # end of optional handling for multi line json
          echo "::set-output name=packageJson::$content"
      - run: |
          echo "${{fromJson(steps.set_var.outputs.packageJson).version}}"

Multi line JSON handling as per https://github.community/t5/GitHub-Actions/set-output-Truncates-Multiline-Strings/td-p/37870

GitHub issue about set-env / set-output multi line handling: https://github.com/actions/toolkit/issues/403

like image 182
riQQ Avatar answered Sep 19 '22 19:09

riQQ


Use a multi line environment variable:

- run: |
  echo 'PACKAGE_JSON<<EOF' >> $GITHUB_ENV
  cat ./package.json >> $GITHUB_ENV
  echo 'EOF' >> $GITHUB_ENV
- run: |
  echo '${{ fromJson(env.PACKAGE_JSON).version }}'

This avoids any need for escaping.

like image 22
dastrobu Avatar answered Sep 20 '22 19:09

dastrobu