Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

github action combine workflow_dispatch and push in the same workflow

I am trying to figure out how to combine manual trigger and other trigers (push for example) in the same workflow

This is my manual action


on:
  workflow_dispatch:
    inputs:
      environment:
        type: environment
        default: DEV
        required: true

env:
  ENVIRONMENT: ${{ github.event.inputs.environment }}
.
.
.

I want something like

on:
  push:
    branches:
    - main
    - dev
  workflow_dispatch:
    inputs:
      environment:
        type: environment
        default: DEV
        required: true

env:
  ENVIRONMENT: ${{ github.event.inputs.environment }} or {{ DEV if dev }} or {{ PROD if main }}
.
.
.

like image 289
Ofer Helman Avatar asked Nov 23 '25 02:11

Ofer Helman


2 Answers

Here's one way to do it:

name: Print environment variable

on:
  push:
    branches:
      - master
      - development
  workflow_dispatch:
    inputs:
      environment:
        type: string
        default: DEV
        required: true

jobs:    
  prod:
    if: ${{ github.event_name == 'push' && github.ref_name == 'master' || github.event.inputs.environment == 'PROD' }}
    env:
      environment: PROD
    runs-on: ubuntu-latest
    steps:
      - name: Print value
        run: echo ${{ env.environment }}
        
  dev:
    if: ${{ github.event_name == 'push' && github.ref_name == 'development' || github.event.inputs.environment == 'DEV' }}
    env:
      environment: DEV
    runs-on: ubuntu-latest
    steps:
      - name: Print value
        run: echo ${{ env.environment }}

Of course, if you have the same steps for both environments and do not wish to repeat them then consider using reusable workflows.

UPDATE:

Just to clarify why I used type string for environment. Yes, I've noticed that you used environment as type for input, but the docs are not quite clear on that part. Here it says that inputs can only be of type boolean, number or string, yet here in the example it shows not only environment type, but also choice type.

like image 120
frennky Avatar answered Nov 26 '25 19:11

frennky


according to docs, you can setup an env variable with:

echo "{environment_variable_name}={value}" >> $GITHUB_ENV

so in your case something like this should work (did not test):

steps:
  - name: Checkout
    uses: actions/checkout@v2
  - name: Set env
    run: |-
      echo "ENVIRONMENT=$(
      if ${{ github.event.inputs.environment }}; then
        echo ${{ github.event.inputs.environment }}
      elif [ ${{ github.ref_name }} == dev]; then
        echo DEV
      elif [ ${{ github.ref_name }} == main]; then
        echo PROD
      fi
      )" >> $GITHUB_ENV
  - name: Test env
    run: echo "woo!!" ${{ env.ENVIRONMENT }}
like image 20
a.k Avatar answered Nov 26 '25 21:11

a.k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!