github操作将workflow_dispatch和push结合在同一个工作流程中

Ofe*_*man 18 github-actions

我试图弄清楚如何在同一工作流程中结合手动触发器和其他触发器(例如推送)

这是我的手动操作


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

env:
  ENVIRONMENT: ${{ github.event.inputs.environment }}
.
.
.
Run Code Online (Sandbox Code Playgroud)

我想要类似的东西

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 }}
.
.
.

Run Code Online (Sandbox Code Playgroud)

fre*_*nky 8

这是一种方法:

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 }}
Run Code Online (Sandbox Code Playgroud)

当然,如果您对两种环境都有相同的步骤并且不希望重复它们,那么请考虑使用可重用的工作流程

更新:

只是为了澄清为什么我使用类型string作为环境。是的,我注意到您用作environment输入类型,但文档对此部分不太清楚。这里它说输入只能是类型boolean,numberstring,但示例中它不仅显示environment类型,还显示choice类型。


a.k*_*a.k 5

根据文档,您可以使用以下命令设置环境变量:

echo "{environment_variable_name}={value}" >> $GITHUB_ENV
Run Code Online (Sandbox Code Playgroud)

所以在你的情况下,这样的事情应该有效(未测试):

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 }}
Run Code Online (Sandbox Code Playgroud)