Reusable GitHub actions
The workflow_call parameter allows you to create reusable workflows that can be invoked from other workflows in the same or different repositories.
Let's not beat around the bush and get straight to the examples.
Creating a reusable workflow
A reusable workflow that accepts inputs and secrets is created like this (code for the file .github\workflows\action_file_name.yml
):
name: Reusable Workflow on: workflow_call: inputs: username: required: true type: string secrets: secret_token: required: true jobs: build: runs-on: ubuntu-latest steps: - run: echo "Hello, ${{ inputs.username }}!" - run: echo "Using secret: ${{ secrets.secret_token }}."
Docs for workflow_call.
Invoking a reusable workflow
Now you can invoke the created workflow from another workflow by passing data and secrets like this:
name: Call Reusable Workflow on: push: branches: - main jobs: invoke_reusable_workflow: uses: ./.github/workflows/reusable.yml with: username: 'JohnDoe' secrets: secret_token: ${{ secrets.MY_SECRET }}
Invoking from another repository
Invokes a reusable workflow from another repository:
jobs: invoke_reusable_workflow: uses: my-org/my-repo/.github/workflows/reusable.yml@main with: username: 'JaneDoe' secrets: secret_token: ${{ secrets.MY_SECRET }}
Inputs and secrets
Defining inputs and secrets for the reusable workflow:
on: workflow_call: inputs: username: required: true type: string secrets: api_token: required: true
Using outputs
The workflow sets outputs that can be used by the invoking workflow.
on: workflow_call: jobs: calculate: runs-on: ubuntu-latest outputs: result: ${{ steps.calculate_output.outputs.result }} steps: - id: calculate_output run: echo "::set-output name=result::42"
The invoking workflow uses the outputs of the reusable workflow.
jobs: use_output: uses: ./.github/workflows/reusable.yml outputs: result: ${{ steps.calculate_output.outputs.result }} runs-on: ubuntu-latest steps: - run: echo "The result is ${{ result }}"
Conclusion
In this article, we explored the use of workflow_call in GitHub Actions to create reusable workflows. Using reusable workflows simplifies the automation process, increases efficiency, reduces code duplication, and ensures adherence to the DRY principle. Reusable workflows can be defined in one repository and then invoked from other workflows in the same or different repositories. We also discussed how to pass inputs and secrets to such workflows, as well as how to use outputs. These examples and tips will help you set up CI/CD processes in GitHub Actions for automating and standardizing project work. Using GitHub Actions and workflow_call is a powerful way to enhance the support and scalability of your project, especially when managing a large number of repositories and processes.