Schedule housekeeping with GitHub Actions
In this task you'll clean up merged branches and old workflow artefacts on a schedule.
Repositories collect clutter: merged branches nobody deleted, old workflow runs, artefacts, stale issues. A scheduled workflow (on: schedule, with cron) can tidy them every night, with workflow_dispatch so you can run it by hand and a dry run option to see what it would do.
Give it the narrowest permissions it needs, for example contents: write to delete branches, and never let it touch protected branches.
Example. Harbourline Design's main repository had 340 merged branches. A nightly housekeeping workflow now deletes branches merged more than a week ago and posts a short summary to the job log.
Before you start
You need: A GitHub repository. Time: 20 minutes.
Where to look
- Repository
- Actions
- New workflow
Steps
- Add a workflow with
on: schedule(cron, in UTC) andworkflow_dispatchwith a dry-run input. - Set
permissions:to only what it needs. - List branches merged into main (excluding main itself) and delete them, or just print them in a dry run.
- Run it by hand once with dry run on, check the list, then let the schedule take over.
Commands
# Branches already merged into main (what a housekeeping job would delete)
git fetch --prune
git branch -r --merged origin/main | grep -v -E 'origin/(main|HEAD)'
Watch out for
- Cost
- Free on public repositories; private repositories use Actions minutes.
- Security
- Use the workflow's GITHUB_TOKEN with minimal permissions, not a personal token.
- Common mistakes
- Deleting unmerged branches, and schedules that run every minute.
Clean up
Delete the workflow file to stop it.
Words to know
- Scheduled workflow
- A GitHub Actions workflow started by a cron schedule instead of an event.
- Dry run
- Running automation so it reports what it would do without changing anything.
- Merged branch
- A branch whose commits are all already in main.
Tick off each step and track your progress in the guide.
Open this task in DevOps, Hands On