Skip to content

Conditionally run GitHub Actions based on PR labels

Posted on:November 18, 2023 at 07:36 PM

This blog post explores how to make GitHub Actions perform specific tasks based on labels in pull requests. Imagine using GitHub Actions to deploy a Node.js app, where certain tasks only run if a particular label, like deploy is on a pull request. However, there’s a snag: you can’t directly use environment variables in job conditions due to a GitHub Actions limitation.

On the official `actions/runner“ repository, an ongoing issue, documented in the GitHub issue, highlights the constraint of accessing env across all workflow fields. This issue, initiated in May 2020, has amassed nearly 50 comments.

To work around this, a middleman job helps by turning the desired environment variable into an output. This output becomes accessible using needs.{jobname}.outputs.{namevar}. So, changes in PR labels can now trigger job execution, making the workflow more dynamic.

Here’s an example of how you could set up your workflow YAML:

name: Node.js CI

on:
  push:
    branches: [main]
  pull_request:
    types: ["labeled", "opened", "synchronize", "reopened"]

env:
  SHOULD_RELEASE: ${{(github.ref == 'refs/heads/main' || contains(github.event.pull_request.labels.*.name, 'deploy')) }}

jobs:
  prepare:
    runs-on: ubuntu-latest
    outputs:
      should_release: ${{ env.SHOULD_RELEASE }}
    steps:
      - name: Print env variable
        run: |
          echo "SHOULD_RELEASE: ${{ env.SHOULD_RELEASE }}"

  release:
    name: Create Github Release
    runs-on: ubuntu-latest
    if: needs.prepare.outputs.should_release == 'true' # Utilizing output from `prepare` job
    needs: [prepare]
    steps:
      - run: echo 'deploy'

The crucial part here is the prepare job, which turns the necessary environment variable into an output. This solves the issue of directly using environment variables in job conditions, allowing for more controlled job execution based on changing PR labels.

By managing workflow dependencies and using outputs, GitHub Actions become a powerful tool for creating customized CI/CD pipelines. Changes in PR labels can now trigger specific job runs, ensuring a smooth and adaptable workflow.