Skip to content

Reusable Workflow Simple Example

olsido edited this page Aug 4, 2024 · 1 revision

Use Case

Reusable workflows allow you to define a set of actions once and reuse them across multiple workflows, promoting DRY (Don’t Repeat Yourself) principles. This is particularly useful for common tasks like setting up the environment, running tests, or deploying applications, which can be standardized and reused in different workflows.

Implementation

Parent Workflow (.github/workflows/reusable-workflow-simple-example–parent-workflow.yml)

name: Reusable Workflow Simple Example - Parent Workflow  # The name of the workflow for identification

on:
  workflow_dispatch:  # Specifies that the workflow can be manually triggered

jobs:
  before-child-workflow:  # Job to be executed before calling the child workflow
    runs-on: ubuntu-latest  # Runs on the latest version of an Ubuntu runner
    steps:
      - name: Echo before calling Child  # Step name describing the action
        run: echo "This is the parent workflow, before calling the child workflow."  # Command to echo a message

  child-workflow:  # Job to call the child workflow
    needs: before-child-workflow  # Ensures this job runs after the 'before-child-workflow' job completes
    uses: ./.github/workflows/reusable-workflow-simple-example--child-workflow.yml  # Specifies the reusable workflow to be called

  after-child-workflow:  # Job to be executed after the child workflow has completed
    needs: child-workflow  # Ensures this job runs after the 'child-workflow' job completes
    runs-on: ubuntu-latest  # Runs on the latest version of an Ubuntu runner
    steps:
      - name: Echo after calling Child  # Step name describing the action
        run: echo "This is the parent workflow, after the child workflow has completed."  # Command to echo a message

View on Gist       View in this repo

Child Workflow (.github/workflows/reusable-workflow-simple-example–child-workflow.yml)

name: Reusable Workflow Simple Example - Child Workflow  # The name of the child workflow for identification

on:
  workflow_call:  # Specifies that this workflow can be called by another workflow

jobs:
  echo-from-child:  # Job in the child workflow
    runs-on: ubuntu-latest  # Runs on the latest version of an Ubuntu runner
    steps:
      - name: Echo from Child  # Step name describing the action
        run: echo "This is the child workflow."  # Command to echo a message

View on Gist       View in this repo

The parent workflow triggers the reusable workflow using the uses keyword. This setup ensures that any changes to the reusable workflow are automatically applied wherever it is used, reducing redundancy and maintenance efforts. By centralizing common tasks in a reusable workflow, you can streamline your CI/CD pipeline and ensure consistency across multiple projects.

Clone this wiki locally