[CI/CD](EN) Setting default value when not using workflow_dispatch and workflow_call

Setting default value when not using workflow_dispatch and workflow_call


Environment and Prerequisite

  • Github Actions


Background

  • In GitHub Actions, there was an issue where the inputs defined in workflow_dispatch and workflow_call could not be used when triggered by other events like push. To address this, it seems that setting default value could be a potential solution so I wrote this.


Solution

  • In cases when inputs cannot be used like push because it is not triggered by workflow_dispatch or workflow_call, you can set default values as shown below.
  • For workflows triggered by workflow_dispatch or workflow_call, the values specified in inputs are used. Otherwise the default value following || is used.
  • Save default value to environment variable and use it.

Code

name: Workflow Return Test
on:
  push:
    branches: [ main ]
  workflow_call:
    inputs:
      key:
        type: string
  workflow_dispatch:
    inputs:
      key:
        type: string
jobs:
  print_default_value_test:
    name: print value
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
      - name: Set default value
        run: |
          echo "VALUE_NAME=${{ inputs.key || "default value" }}" >> $GITHUB_ENV
      - name: Print value
        run: echo "${{ env.VALUE_NAME }}"

Result

  • Triggered by push
Run echo "default value"
  echo "default value"
  shell: /usr/bin/bash -e {0}
  env:
    VALUE_NAME: default value
default value
  • Triggered by workflow_dispatch or workflow_call with passing string value “test input value”
Run echo "test input value"
  echo "test input value"
  shell: /usr/bin/bash -e {0}
  env:
    VALUE_NAME: test input value
test input value


Opinion

I’m not sure if this is the recommended one but I used it because I found it by searching.


Reference