How to split GitHub Actions workflow.yml into multiple files?
GitHub Actions provide a powerful platform for automating software workflows directly in your GitHub repository. As your project grows, it’s common for your GitHub Actions configuration to become complex. One way to manage this complexity is by splitting your workflows into multiple yml
files. This post will walk you through the process of doing just that.
Understanding GitHub Actions Workflows
Each workflow in GitHub Actions is defined in a separate YAML file (.yml
or .yaml
) in the .github/workflows
directory of your repository. A workflow file defines a single workflow, which can contain one or more jobs. Each job can have one or more steps.
The ability to create multiple workflow files is built into GitHub Actions. Each workflow can react to different GitHub events (like push
, pull_request
, etc.), and each can contain its own jobs and steps.
Splitting Workflows into Multiple Files
Let’s assume you have a single workflow that runs tests and then deploys your code if the tests are successful. The workflow.yml
file might look something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
name: Test and Deploy on: [push] jobs: test: runs-on: ubuntu-latest steps: - name: Run tests run: npm test deploy: runs-on: ubuntu-latest needs: test steps: - name: Deploy to production run: npm run deploy |
We can split this workflow into two separate workflows: one for testing and one for deployment.
The test.yml
workflow might look like this:
1 2 3 4 5 6 7 8 9 10 |
name: Run Tests on: [push] jobs: test: runs-on: ubuntu-latest steps: - name: Run tests run: npm test |
The deploy.yml
workflow could look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
name: Deploy on: push: branches: - master jobs: deploy: runs-on: ubuntu-latest steps: - name: Deploy to production run: npm run deploy |
In this case, the Run Tests
workflow is triggered on every push, and the Deploy
workflow is only triggered on pushes to the master
branch.
By splitting workflows into separate files, you can control when they run and make it easier to manage your GitHub Actions configuration.
Conclusion
Splitting a monolithic GitHub Actions workflow into multiple files can help maintain order, improve readability, and provide better control over when specific workflows should run. As your project and its automation requirements grow, consider using multiple workflow files to manage complexity.