Do expressions support ternary operators to change their returned value?

Something along these lines…

- name: Create Release
id: create-release
uses: actions/create-release@v1
env:  
GITHUB\_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:  
tag\_name: ${{ env.VERSION }}
release\_name: ${{ env.VERSION }}
draft: false
prerelease: "${{ github.ref != 'refs/heads/master' ? 'true' : 'false' }}"

Hi @atrauzzi , 

Expressions don’t support ternary operators. You could create a feedback for this feature in the Feedback form for GitHub Actions .

As a workaround , you could add another step to set prerelease as true or false before Create Release step. In my example , I use set-output command to set an output variable in the front step, then use it in Create Release step .

- name: prerelease or not
  id: pre_or_not
  run: |
    if [$REF == 'refs/heads/master']
    then
        echo "::set-output name=prerelease::true"
    else
        echo "::set-output name=prerelease::false"
    fi
  env:
    REF: ${{ github.ref }}

- name: Create Release
  id: create-release
  uses: actions/create-release@v1
  env:
    GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
  with:
    tag_name: ${{ env.VERSION }}
    release_name: ${{ env.VERSION }}
    draft: false
    prerelease: ${{ steps.pre_or_not.outputs.prerelease }}
5 Likes

Is a ternary operator or substitute even necessary in this case?

github.ref != 'refs/heads/master' evaluates to a boolean (true or false). Can’t you just use that?

prerelease: ${{ github.ref != 'refs/heads/master' }}

In other cases, the data type might not be right for you or undesired coercion might occur. In conjunction with comparison operators, GitHub will cast them to numbers (0 or 1), but in case of functions, at least some cast to string ('true' or 'false').

You can cast booleans to strings explicitly should it be necessary:

${{ format(github.ref != 'refs/heads/master') }}

I verified that the cast works like so:

- name: Cast to string
  run: |
    cat <<EOF
      ${{ toJSON(true) }}
      ${{ toJSON(format(true)) }}
    EOF

Because JSON has native boolean types, true remains true when calling toJSON(). The format() function casts it to a string, which then leads to a JSON serialization of "true" (note the double quotes). The wrapping cat <<EOF ... EOF preserves the quote marks, whereas echo would swallow them.

Finally, I want to point out that there is a fake ternary technique which works on GitHub:

${{ github.ref != 'refs/heads/master' && 'true' || 'false' }}

The only limitation is that the second AND condition (here: 'true') must be a truthy value. If it’s falsey (null, false, 0, '') then the value to the right of the OR operator will be returned, regardless of the first condition. There is no nullish coalescing operator ?? to lift this limitation.

Other techniques involving arrays or objects aren’t possible because expressions in Actions do not support array and object literals (yet).

1 Like