Reusable Workflows in GitHub Actions
1. Introduction
GitHub Actions enables developers to automate workflows directly from their GitHub repositories. Reusable workflows allow teams to create workflows that can be shared across multiple repositories, promoting consistency and efficiency in CI/CD processes.
2. Key Concepts
- Workflow: A configurable automated process made up of one or more jobs.
- Job: A set of steps that execute on the same runner.
- Reusable Workflow: A workflow defined in one repository that can be called from another workflow.
3. Creating Reusable Workflows
To create a reusable workflow, you need to define it in a YAML file and specify the necessary inputs. Here’s how to create a reusable workflow step by step:
-
Create a new workflow file in your repository, e.g.,
.github/workflows/reusable.yml
. -
Define the workflow with the
workflow_call
trigger:name: Reusable Workflow on: workflow_call: inputs: input1: required: true type: string
-
Add jobs to the workflow:
jobs: example_job: runs-on: ubuntu-latest steps: - name: Echo input run: echo "Input was: ${{ inputs.input1 }}"
- Commit and push the workflow file to your repository.
4. Example
Here’s how to call a reusable workflow from another workflow:
name: Main Workflow
on: [push]
jobs:
call_reusable_workflow:
uses: user/repo/.github/workflows/reusable.yml@main
with:
input1: 'Hello, World!'
5. Best Practices
- Keep workflows modular to increase reusability.
- Document inputs and outputs clearly in the workflow file.
- Version your reusable workflows to prevent breaking changes.
- Test reusable workflows in a safe environment before deploying.
6. FAQ
What are the limitations of reusable workflows?
Reusable workflows cannot use environment variables defined in the calling workflow.
Can I pass secrets to reusable workflows?
Yes, you can pass secrets as inputs by using the secrets
context.
Can reusable workflows call other workflows?
No, reusable workflows cannot call other workflows, but they can be called by other workflows.