Reusing GitHub Actions Workflows with Workflow Call
GitHub Actions provides a robust platform for automating workflows directly in your GitHub repositories. For larger projects with complex workflows, you might find that you have repeating segments of code in your workflows. Duplicating code is rarely a good idea as it leads to maintenance headaches and can result in errors. The “workflow call” feature in GitHub Actions is a way to promote reuse and reduce duplication. This blog post will guide you through the process of including one workflow.yaml
into another using this feature.
Understanding Workflow Calls in GitHub Actions
GitHub Actions introduced the workflow call syntax to allow the reuse of workflows across different repositories. You can call a workflow and pass inputs to it. You can also use outputs from the called workflow in your calling workflow.
A workflow that will be used in a workflow call is written as any other workflow, but with the inclusion of the inputs
and outputs
keys to accept inputs and produce outputs.
Creating a Reusable Workflow
Let’s create a reusable workflow that we’ll call from another workflow. We’ll create a workflow that lints our JavaScript code.
In your repository, create a new workflow file named lint-code.yml
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
name: Lint Code on: workflow_call: jobs: lint: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Use Node.js uses: actions/setup-node@v2 with: node-version: 14 - name: Install dependencies run: npm ci - name: Run linter run: npm run lint |
In this workflow, on: workflow_call
means that this workflow is designed to be called from other workflows.
Calling a Workflow from Another Workflow
Now, let’s create another workflow that will call our lint-code.yml
workflow:
1 2 3 4 5 6 7 8 9 |
name: Build and Test on: [push, pull_request] jobs: call-linter: uses: ./.github/workflows/lint-code.yml secrets: github_token: ${{ secrets.GITHUB_TOKEN }} |
In this workflow, uses: ./.github/workflows/lint-code.yml
indicates that we’re calling the lint-code.yml
workflow located in the .github/workflows/
directory of the current repository.
Conclusion
GitHub Actions’ “workflow call” syntax is a powerful feature that enables you to reuse workflows across your repository, promoting code reuse and reducing duplication. You can use it to create workflows that handle common tasks and call them from other workflows, creating a modular and maintainable CI/CD setup.