If Else in Github action

Viewed 2864

I am following this.

https://github.community/t/github-actions-manual-trigger-approvals/16233/83

  - name: Clone Repository (Latest)
    uses: actions/checkout@v2
    if: github.event.inputs.git-ref == ''
  - name: Clone Repository (Custom Ref)
    uses: actions/checkout@v2
    if: github.event.inputs.git-ref != ''
    with:
      ref: ${{ github.event.inputs.git-ref }}

This works fine but multiple-step makes the workflow bigger. I was trying something more compact.

like determining the commit SHA in env.

env:
  COMMIT_HASH: ${{ github.event.inputs.git-ref != '' && github.event.inputs.git-ref || github.sha }}

this works fine but looks like a ugly hack to me. any suggestions. I am trying to avoid extra steps,tha's all.

1 Answers

You could consider using the haya14busa/action-cond action.

It is useful when the if-else operation is needed to set dynamic configuration of other steps (don't need to duplicate the whole step to set different values in a few parameters).

Examples:

- name: Determine Checkout Depth
  uses: haya14busa/action-cond@v1
  id: fetchDepth
  with:
    cond: ${{ condition }}
    if_true: '0'  # string value
    if_false: '1' # string value
- name: Checkout
  uses: actions/checkout@v2
  with:
    fetch-depth: ${{ steps.fetchDepth.outputs.value }}

or

steps:
- uses: haya14busa/action-cond@v1
  id: condval
  with:
    cond: ${{ github.event_name == 'pull_request' }}
    if_true: "value for pull request event"
    if_false: "value for non pull request event"
- name: Use conditional value
  run: echo "${{ steps.condval.outputs.value }}"
Related