Home > Blockchain >  How to write conditional expressions in GitHub Actions
How to write conditional expressions in GitHub Actions

Time:09-08

I am trying to understand the logic behind the following line from the GitHub docs:

runs-on: ${{ fromJSON('["ubuntu-latest", "self-hosted"]')[github.repository == 'github/docs-internal'] }}

GitHub's explanation of what this line does makes sense: if the repository running the workflow is named 'github/docs-internal' then a self-hosted runner is used. If the github repo is any other name then the workflow will use a managed ubuntu runner.

I am looking for an explanation as to why the fromJSON function is being used, and why the second value (self-hosted) is used if the condition is true and why the first value (ubuntu-latest) is used if the condition is false.

Suppose I wanted to add an additional condition to use a windows runner if the repository name was 'github/docs-external.' Would the new line look something like this:

runs-on: ${{ fromJSON('["ubuntu-latest", "self-hosted", "windows-latest"]')[github.repository == 'github/docs-internal'][github.repository == 'github/docs-external'] }}

CodePudding user response:

Trying to explain:

${{ fromJSON('["ubuntu-latest", "self-hosted"]')[github.repository == 'github/docs-internal'] }}

the fromJSON will return an array

fromJSON('["ubuntu-latest", "self-hosted"]')

the: github.repository == 'github/docs-internal' will return a boolean condition true/false that is interpreted in 0 or 1 So this hack will help accessing to the element with index 0 or 1 of the array.

In order to implement your new requirement, you should find a way to return a value like 2.

Or, thanking inspiration by this thread https://github.com/actions/runner/issues/409, you could first rewrite in an if/else way, like:

runs-on: ${{ github.repository == 'github/docs-internal &&  "self-hosted" || "ubuntu-latest" }}

Then try to add an additional condition, like (not tested):

runs-on: ${{ github.repository == 'github/docs-internal &&  "self-hosted" || (github.repository == 'github/docs-external &&  "windows-latest" ||  "ubuntu-latest" )  }}

  • Related