Guide to Reusable GitHub Actions Workflow

Code One Action at a Time

Posted by varunrayen on Sunday, May 14, 2023

What is Github Actions?

GitHub Actions is a tool that lets you automate your software workflows right in GitHub repository. It can be set up to do things like build, test, and deploy your projects.

One of the most notable features of GitHub Actions is the ability to create reusable workflow. These are workflows that you can use across multiple projects without having to make a new one. Understanding Reusable Workflows

Just like regular workflows, reusable workflows are defined in dedicated directories .github/workflows They are made up of one or more jobs that each have a set of steps to take a specific task. It is possible to use a reusable workflow in the same repository where it is defined or can be referenced by workflows in other repositories, facilitating workflow reuse and reducing duplication.

Creating a Reusable Workflow

To start making a reusable workflow, you will have to put it in a .yml or .yaml file in your .github/workflows repositories directory.

Let’s create a simple reusable workflow that runs unit tests for a Node.js application.

name: 'Node.js CI'
        required: true
        type: string
        required: true

    runs-on: ubuntu-latest
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v2
          node-version: ${{ inputs.node-version }}
      - run: npm ci
      - run: npm test
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

In this example, the workflow_call event triggers the workflow when it is called by another workflow. The inputs and secrets sections define the input parameters and secrets that the workflow expects when it is called.

Calling a Reusable Workflow

To call a reusable workflow, you will need to use the uses keyword in your workflow file. The uses keyword takes the path to the reusable workflow file and the input parameters and secrets that the workflow expects.

name: 'Use Reusable Workflow'
on: [push, pull_request]

    uses: org/repo/.github/workflows/nodejs-ci.yaml@main
      node-version: '14'
      NPM_TOKEN: ${{ secrets.NPM_TOKEN }}

In this example, the uses keyword is used to specify the repository (org/repo), the path to the workflow file, and the branch (@main). The with keyword is used to pass input parameters, and the secrets keyword is used to pass secrets.

Advantages of Reusable Workflows

Using reusable workflows can offer several advantages:

  • Consistency: Reusable workflows ensure consistency across your projects, as the same set of CI/CD instructions are used in all repositories.
  • Reduced Errors: As workflows are reused, the likelihood of errors decreases as the need to re-write workflows for each repository is eliminated.
  • Improved Efficiency: Reusable workflows save time and effort as you don’t have to write and debug new workflows for each repository.