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'
-
on
Section: Initiates the workflow upon pushes to the main branch and specific pull request events, such as opening, creation, reopening, and changes in labels. -
env
Section: Establishes theSHOULD_RELEASE
environment variable, crucial for executing jobs conditionally.- Verifies if the workflow is on the main branch using
github.ref == 'refs/heads/main'
. - Confirms the presence of the ‘deploy’ label in PR labels using
contains(github.event.pull_request.labels.*.name, 'deploy'))
.
- Verifies if the workflow is on the main branch using
-
jobs
Section: Contains customized jobs for the workflow.prepare
Job: Generates an output variableshould_release
based on theSHOULD_RELEASE
environment variable. This output is pivotal for subsequent conditional job execution.release
Job: The job’s execution is determined by theif
condition, utilizingneeds.prepare.outputs.should_release
.
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.