Home > database >  GitHub Actions - run step only if job was triggered by specific "on" trigger
GitHub Actions - run step only if job was triggered by specific "on" trigger

Time:04-13

I have an action that lints the code and runs tests when a commit to master happens and on pull requests:

name: My Action

on:
  push:
    branches: [master]
  pull_request:
    branches: [master]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Use Node.js 16
        uses: actions/setup-node@v2
        with:
          node-version: 16
      - run: npm install
      - run: npm run lint
      - run: npm test

I want to add a "deploy" step at the end that only runs when the action is triggered by a commit to master, but not on pull requests (and ideally that doesn't run if the linting isn't successful). Do I just have to make two separate files?

CodePudding user response:

You can use conditionals on steps to turn them off in specific cases:

if: ${{ github.event_name == 'pull_request' }}

In your case you probably want to check for push:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Use Node.js 16
        uses: actions/setup-node@v2
        with:
          node-version: 16
      - run: npm install
      - run: npm run lint
      - run: npm test
      - run: deploy
        if: ${{ github.event_name == 'push' }}

See:

As long as your linting step returns non-0, it should already fail the workflow.

  • Related