The GitHub Repository Playbook: Branching, Rulesets, Security, Releases and Recovery for a DevOps Project
A practical playbook for running a project on GitHub: branching, rulesets, security scanning, versioned releases, issue management, backups and disaster recovery, docs and standards.
- Author
- Navinda Chandrasiri
- Published
- Reading time
- 24 min read

On this page
- The principles behind every decision
- Start with a sensible baseline
- Branching strategy
- Naming branches
- Commit messages that machines can read
- Protect the code with rulesets
- A baseline ruleset for main
- Protect your tags too
- A required-checks trap, and the fix
- Code review and ownership
- Security: defence in layers
- People and access
- Secrets: stop them leaking in the first place
- Code scanning with CodeQL
- Dependencies: Dependabot and dependency review
- Harden the pipeline itself
- Prove what you shipped
- Tell people how to report problems
- Vulnerability management is a process, not a scanner
- Releasing and version management
- Use Semantic Versioning
- Let automation cut the release
- Make the release notes useful
- Hotfixes and older versions
- Issue and project management
- Use issue forms, not blank boxes
- A small, consistent label set
- Run triage and planning on a board
- Backup, recovery and disaster recovery
- Know what git protects and what it does not
- Set recovery goals first
- Follow the 3-2-1 idea
- An automated backup you can adopt today
- Keep your settings as code
- Restoring from a mirror
- Disaster scenarios and responses
- Documentation that people actually use
- Standards that remove arguments
- A maintenance rhythm
- The setup checklist
- Wrapping up
A repository is not just a folder of code. It is the place where your code, your review process, your security posture, your release history and your team's habits all live. When it is set up well, a new contributor ships a safe change on day one. When it is set up badly, every release is a small adventure, and every incident starts with "who has permission to fix this?".
This post is a playbook for setting up and maintaining a GitHub repository the way a DevOps team would. It covers branching, rulesets, security, releases, issues, backup and disaster recovery, documentation and standards, with copy-and-paste configuration for each. The companion post, A Repository That Explains Itself: The Ideal GitHub Project Structure for DevOps Teams, covers what the files and folders should look like.
GitHub moves fast. Menu names, plan limits and action versions change, so treat the snippets as a starting point, check the current GitHub documentation, and use the latest major version of each action you adopt. Some features (private-repository code scanning, organisation-level rulesets and similar) depend on your plan.
The principles behind every decision#
Every setting below comes back to five ideas:
- Everything is code. Application, infrastructure, workflows, repository settings and documentation all live in version control, so they are reviewable and recoverable.
mainis always releasable. Anything merged is tested, reviewed and safe to ship.- Automate the boring checks. Humans review design and intent. Machines check formatting, tests, secrets and vulnerable dependencies.
- Least privilege everywhere. People, tokens and workflows get the minimum access they need.
- Assume failure. Accounts get compromised, people make mistakes, and services have outages. Have a recovery plan before you need it.
Start with a sensible baseline#
Before branching models and security tooling, fix the repository's own settings. These take ten minutes and prevent a surprising number of problems.
Under Settings, General and the pull request options:
- Default branch:
main. - Merge methods: allow squash merging and set its default message to the pull request title and description. Turn off merge commits. This gives you one clean commit per change.
- Automatically delete head branches: on. Merged branches disappear on their own.
- Allow auto-merge: on. Reviewers can approve and walk away while checks finish.
- Always suggest updating pull request branches: on.
- Wiki and Projects: turn off any you do not use. Fewer surfaces means less to secure and maintain.
Under Settings, Actions, General:
- Workflow permissions: set the default
GITHUB_TOKENto read repository contents only. Each workflow then asks for more explicitly. - Fork pull request workflows: require approval for first-time and outside contributors.
- Allowed actions: restrict to actions created by your organisation and verified creators, plus an explicit allow-list of the rest.
Finally, add a description, topics and a social preview image. They help people (and search engines) find the project, and they cost nothing.
Branching strategy#
There is no single correct model. The right one depends on how you ship.
| Model | Best for | Branch lifetime | Release approach | Trade-off |
|---|---|---|---|---|
| GitHub Flow | Web apps and services that deploy continuously | Hours to days | Deploy from main or from a tag | Simple, but supports one live version |
| Trunk-based | Teams with strong CI and feature flags | Under a day | main is always releasable | Needs flags, fast tests and discipline |
| GitFlow | Versioned products: libraries, mobile apps, on-premise software | Long-lived | develop and release/x.y branches | Heavy process, more merge conflicts |
My default recommendation is GitHub Flow with optional maintenance branches. Work happens on short-lived branches off main, every change goes through a pull request, and main deploys. If you must support more than one version at once, add release/1.x style branches for backported fixes only, and nothing more.
Naming branches#
A predictable name tells reviewers what they are looking at, and lets automation act on it:
feat/123-oauth-login
fix/456-null-pointer-on-checkout
docs/update-contributing-guide
chore/bump-node-22
hotfix/789-payment-timeout
release/1.xUse a type prefix, an issue number when there is one, and a short kebab-case description.
Commit messages that machines can read#
Adopt Conventional Commits. The format is type(scope): summary, for example feat(auth): add OAuth login. It makes history readable and, more importantly, lets tooling decide the next version number and write the changelog for you.
| Commit type | Meaning | Version bump (SemVer) |
|---|---|---|
fix | A bug fix | Patch (1.4.2 to 1.4.3) |
feat | A new feature | Minor (1.4.2 to 1.5.0) |
feat! or a BREAKING CHANGE: footer | An incompatible change | Major (1.4.2 to 2.0.0) |
docs, chore, refactor, test, ci | No user-facing change | Usually no release |
Because you squash-merge, the pull request title becomes the commit message, so that is what you validate. A small check does it:
name: PR title
on:
pull_request:
types: [opened, edited, synchronize, reopened]
permissions:
pull-requests: read
jobs:
semantic-title:
runs-on: ubuntu-latest
steps:
- uses: amannn/action-semantic-pull-request@v5
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}Protect the code with rulesets#
Rulesets are GitHub's modern way to enforce rules on branches, tags and pushes. They improve on classic branch protection in ways that matter for a team:
- Several rulesets can apply at once, and the strictest rule wins, so you can layer a baseline with extra rules.
- They have a bypass list, so exceptions are explicit and audited rather than hidden in an admin toggle.
- You can define them at the organisation level and apply them to many repositories (on plans that support it).
- Some plans offer an evaluate mode that shows what a ruleset would have blocked before you enforce it.
- They can be exported and imported as JSON, so they are reviewable and repeatable.
A baseline ruleset for main#
This JSON describes a solid default. You can paste its contents into the ruleset import screen, or create it from the command line:
{
"name": "Protect main",
"target": "branch",
"enforcement": "active",
"conditions": {
"ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] }
},
"bypass_actors": [],
"rules": [
{ "type": "deletion" },
{ "type": "non_fast_forward" },
{ "type": "required_linear_history" },
{
"type": "pull_request",
"parameters": {
"required_approving_review_count": 1,
"dismiss_stale_reviews_on_push": true,
"require_code_owner_review": true,
"require_last_push_approval": true,
"required_review_thread_resolution": true
}
},
{
"type": "required_status_checks",
"parameters": {
"strict_required_status_checks_policy": true,
"required_status_checks": [{ "context": "ci-gate" }]
}
}
]
}gh api --method POST repos/my-org/my-project/rulesets --input protect-main.jsonWhat each rule buys you:
deletionandnon_fast_forwardstop anyone deletingmainor force-pushing over its history.required_linear_historykeeps history straight, which matches squash merging.pull_requestrequires a review. Dismissing stale approvals on new pushes, and requiring approval of the most recent push, close the trick of getting a harmless change approved and then adding something else.require_code_owner_reviewbrings in the right experts through theCODEOWNERSfile (more on that below).required_status_checksblocks merging until CI passes, and with the strict setting, until the branch is up to date withmain.
Keep the bypass list empty or as small as you can. If someone genuinely needs an exception, choose the "pull requests only" bypass mode so that even administrators still go through a review.
Protect your tags too#
Release tags are your audit trail. If v1.4.2 can be moved or deleted, you cannot trust what shipped. Add a second ruleset for tags:
{
"name": "Protect release tags",
"target": "tag",
"enforcement": "active",
"conditions": {
"ref_name": { "include": ["refs/tags/v*"], "exclude": [] }
},
"bypass_actors": [],
"rules": [
{ "type": "deletion" },
{ "type": "update" },
{ "type": "non_fast_forward" }
]
}A required-checks trap, and the fix#
If your CI uses path filters (for example, only run tests when src/ changes), a required check that never runs stays "pending" forever and blocks the pull request. The robust pattern is a single gate job that always runs and summarises the others, and you require only that one:
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci && npm run lint
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci && npm test
ci-gate:
if: always()
needs: [lint, test]
runs-on: ubuntu-latest
steps:
- name: Fail if any required job failed or was cancelled
run: |
if [[ "${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') }}" == "true" ]]; then
exit 1
fiSkipped jobs count as success, failures do not, and the ruleset only ever asks for ci-gate. Required checks match on the job name shown in the pull request checks list.
Code review and ownership#
Reviews work when it is obvious who should look at what. A CODEOWNERS file maps paths to people or teams:
# .github/CODEOWNERS
# The last matching pattern wins.
* @my-org/maintainers
/.github/ @my-org/platform-team
/infra/ @my-org/platform-team
/docs/ @my-org/docs-team
/src/payments/ @my-org/payments-team @aliceNote the entry for /.github/. Anyone who can change a workflow can change what runs with your secrets, so workflow changes deserve platform-team review.
Add a pull request template so every change answers the same questions:
<!-- .github/pull_request_template.md -->
## What and why
<!-- What does this change do, and why is it needed? Link the issue: Fixes #123 -->
## How was it tested?
- [ ] Unit tests added or updated
- [ ] Tried it locally or in a preview environment
## Checklist
- [ ] PR title follows Conventional Commits
- [ ] Docs updated if behaviour changed
- [ ] No secrets, tokens or personal data in the diff
- [ ] Breaking changes are called out aboveKeep pull requests small. A reviewer can genuinely read 200 changed lines. Nobody genuinely reads 2,000.
Security: defence in layers#
No single control keeps a repository safe. Think in layers, so that one failure does not become a breach.
| Layer | What can go wrong | Controls |
|---|---|---|
| People and access | Stolen account, over-broad permissions | Mandatory 2FA or passkeys, SSO, teams over individuals, least-privilege roles |
| Secrets | Keys committed to the repository | Secret scanning, push protection, secret managers, no long-lived credentials |
| Your code | Vulnerabilities you introduce | Code scanning (CodeQL), required review, tests |
| Dependencies | Known-vulnerable or malicious packages | Dependency graph, Dependabot, dependency review on pull requests |
| CI/CD and supply chain | A compromised workflow or action | Read-only token, pinned actions, OIDC, environments, build attestations |
People and access#
Give people the lowest role that lets them work: Read, Triage, Write, Maintain or Admin, assigned through teams rather than one by one. Keep Admin for very few people. Require two-factor authentication across the organisation, ideally with passkeys, and use SSO if you have it.
For automation, prefer GitHub Apps and fine-grained personal access tokens scoped to specific repositories over classic tokens that can touch everything the owner can.
Secrets: stop them leaking in the first place#
Turn on secret scanning and, crucially, push protection, which blocks a push containing a recognised secret before it ever reaches the repository. For private repositories these are paid features on current plans. They are worth it.
When a secret does leak, remember the order of operations: rotate it first. Removing it from the history afterwards is housekeeping, not a fix, because anyone who saw it already has it.
Better still, avoid storing cloud credentials at all. Authenticate workflows to AWS with OIDC, as described in Goodbye Access Keys: Connecting GitHub Actions to AWS with OIDC.
Code scanning with CodeQL#
CodeQL finds common vulnerability patterns (injection, unsafe deserialisation, path traversal) in your own code. The quickest route is Settings, Code security, Code scanning, Default setup. If you want control over languages and schedule, add a workflow:
name: CodeQL
on:
push:
branches: [main]
pull_request:
branches: [main]
schedule:
- cron: "17 3 * * 1" # weekly, catches newly published query packs
permissions:
contents: read
security-events: write
jobs:
analyze:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
language: [javascript-typescript]
steps:
- uses: actions/checkout@v4
- uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
- uses: github/codeql-action/analyze@v3You can also add a ruleset rule that requires code scanning results, so a pull request with a new high-severity finding cannot merge.
Dependencies: Dependabot and dependency review#
Most of your code is other people's code. Three tools cover it:
- Dependabot alerts tell you when a dependency you use has a known vulnerability.
- Dependabot security updates open a pull request with the fix.
- Dependabot version updates keep everything current in small, regular steps, which is far easier than a yearly big-bang upgrade.
Configure version updates in .github/dependabot.yml, and include your workflows and Docker images, not only language packages:
version: 2
updates:
- package-ecosystem: npm
directory: /
schedule:
interval: weekly
open-pull-requests-limit: 5
groups:
dev-dependencies:
dependency-type: development
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
- package-ecosystem: docker
directory: /
schedule:
interval: weeklyThen add dependency review so a pull request that introduces a vulnerable package is blocked at review time:
name: Dependency review
on: pull_request
permissions:
contents: read
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/dependency-review-action@v4
with:
fail-on-severity: highHarden the pipeline itself#
Your workflows are code that runs with access to your secrets and cloud accounts, so they are a prime target. The essentials:
- Start with no permissions. Put
permissions: {}orcontents: readat the top of each workflow and grant more per job. - Pin third-party actions to a full commit SHA, with the version in a comment. Tags can be moved. Commit hashes cannot. Let Dependabot update them.
- Never put untrusted input straight into a shell command. Pull request titles, branch names and issue bodies are attacker-controlled.
# Dangerous: the title is pasted into the script, so a crafted title runs commands
- run: echo "Title is ${{ github.event.pull_request.title }}"
# Safe: the value arrives as an environment variable and is never parsed as code
- env:
PR_TITLE: ${{ github.event.pull_request.title }}
run: echo "Title is $PR_TITLE"- Be very careful with
pull_request_target. It runs with secrets in the context of the base repository. Never check out and run code from an untrusted fork inside it. - Gate production with Environments that require reviewers and restrict deployment branches.
- Lint your workflows. Tools like
actionlintandzizmorcatch injection bugs and risky patterns automatically.
Prove what you shipped#
For released software, publish build provenance. GitHub artifact attestations let consumers verify that a binary or image really came from your repository's workflow:
permissions:
id-token: write
contents: read
attestations: write
steps:
- uses: actions/checkout@v4
- run: npm ci && npm run build && tar -czf dist.tar.gz dist
- uses: actions/attest-build-provenance@v2
with:
subject-path: dist.tar.gzPair it with signed commits and tags, an exported SBOM (software bill of materials) from the dependency graph, and, if you want an outside opinion, the OpenSSF Scorecard action, which grades your repository's practices.
Tell people how to report problems#
Add a SECURITY.md and enable private vulnerability reporting, so researchers can report a flaw privately instead of opening a public issue:
# Security Policy
## Supported versions
| Version | Supported |
| ------- | ------------------ |
| 2.x | Yes |
| 1.x | Security fixes only |
| < 1.0 | No |
## Reporting a vulnerability
Please do not open a public issue. Use GitHub's "Report a vulnerability" button
on the Security tab, or email security@example.com. We aim to acknowledge reports
within 3 working days and to ship a fix for confirmed critical issues within 14 days.Vulnerability management is a process, not a scanner#
Turning on scanners produces alerts. Managing vulnerabilities means deciding what happens next, every time, the same way. A workable lifecycle:
- Detect. Dependabot, code scanning and secret scanning raise alerts in the Security tab.
- Triage. Within a day or two, decide whether each alert is real, reachable and exploitable in your context.
- Fix. Merge the Dependabot pull request, patch the code, or apply a mitigation.
- Verify. Confirm the alert closes after the fix lands on
main. - Communicate. For vulnerabilities in your own released software, publish a security advisory (and request a CVE through GitHub where it applies).
- Learn. Ask how it got in, and whether a rule, test or scan would have caught it earlier.
Agree on response targets and write them down. These numbers are examples, so adjust them to your risk appetite:
| Severity | Target to fix or mitigate | Notes |
|---|---|---|
| Critical | 7 days | Drop other work. Consider an out-of-band release |
| High | 30 days | Schedule it into the current sprint |
| Medium | 90 days | Batch with routine dependency updates |
| Low | Best effort | Fix when touching the area |
Two habits keep the process honest. When you dismiss an alert, always choose a reason and add a comment (for example "not reachable, tracked in issue 482"), so the next person is not guessing. And track a few numbers: open critical and high alerts, and time to remediate. The organisation-level security overview shows these across repositories.
Releasing and version management#
Use Semantic Versioning#
Version numbers are a promise to your users. MAJOR.MINOR.PATCH makes that promise explicit:
- PATCH (1.4.2 to 1.4.3): backwards-compatible bug fixes.
- MINOR (1.4.2 to 1.5.0): backwards-compatible new functionality.
- MAJOR (1.4.2 to 2.0.0): breaking changes.
Use pre-release suffixes such as 1.5.0-rc.1 for candidates, and always tag with a v prefix (v1.5.0) so the tag ruleset above matches.
Let automation cut the release#
Because commits follow Conventional Commits, a tool can read the history, compute the next version, update the changelog and open a release pull request. release-please does exactly that. You merge the release pull request when you are ready to ship, and it creates the tag and the GitHub Release:
name: Release
on:
push:
branches: [main]
permissions:
contents: write
pull-requests: write
jobs:
release-please:
runs-on: ubuntu-latest
outputs:
release_created: ${{ steps.rp.outputs.release_created }}
tag_name: ${{ steps.rp.outputs.tag_name }}
steps:
- id: rp
uses: googleapis/release-please-action@v4
with:
token: ${{ secrets.RELEASE_PLEASE_TOKEN }}
release-type: node
publish:
needs: release-please
if: ${{ needs.release-please.outputs.release_created }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: echo "Build and publish ${{ needs.release-please.outputs.tag_name }} here"One gotcha: pull requests created with the default GITHUB_TOKEN do not trigger other workflows, so your CI would never run on the release pull request. Use a GitHub App token or a fine-grained personal access token, as in RELEASE_PLEASE_TOKEN above.
Make the release notes useful#
GitHub can generate release notes from merged pull requests, grouped by label. Control the grouping with .github/release.yml:
changelog:
exclude:
labels:
- ignore-for-release
authors:
- dependabot[bot]
categories:
- title: Breaking changes
labels: [breaking-change]
- title: New features
labels: [feature, enhancement]
- title: Bug fixes
labels: [bug]
- title: Documentation
labels: [documentation]
- title: Other changes
labels: ["*"]Hotfixes and older versions#
- Hotfix a live problem: branch from the release tag (or
mainif it is still the same), fix, tag a patch release. - Support an older version: keep a
release/1.xbranch, cherry-pick the fix onto it, and tagv1.x.yfrom there. Protect those branches with the same ruleset pattern. - Promote, do not rebuild: build an artifact once, then promote that exact artifact through staging to production. Rebuilding for each environment means you are not shipping what you tested.
- Make releases immutable: protected tags, and where your plan supports it, GitHub's immutable releases, so a published release cannot be silently altered.
Issue and project management#
Good issue hygiene means nothing important is lost and nothing stale lingers.
Use issue forms, not blank boxes#
Issue forms collect the details you actually need. Put them in .github/ISSUE_TEMPLATE/:
# .github/ISSUE_TEMPLATE/bug_report.yml
name: Bug report
description: Something is broken or behaves unexpectedly
title: "[Bug]: "
labels: ["bug", "needs-triage"]
body:
- type: markdown
attributes:
value: Thanks for taking the time to report this. Please search existing issues first.
- type: textarea
id: what-happened
attributes:
label: What happened?
description: What did you expect, and what happened instead?
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce
placeholder: "1. Go to ...\n2. Click ...\n3. See error"
validations:
required: true
- type: input
id: version
attributes:
label: Version
placeholder: v1.4.2
validations:
required: trueAnd a config.yml next to it that disables blank issues and points questions and security reports to the right place:
# .github/ISSUE_TEMPLATE/config.yml
blank_issues_enabled: false
contact_links:
- name: Ask a question
url: https://github.com/my-org/my-project/discussions
about: Questions and ideas belong in Discussions
- name: Report a security vulnerability
url: https://github.com/my-org/my-project/security/advisories/new
about: Please report vulnerabilities privatelyA small, consistent label set#
Too many labels become noise. A compact scheme with a few dimensions covers most teams:
| Dimension | Examples |
|---|---|
| Type | bug, feature, documentation, chore, security |
| Priority | priority: critical, priority: high, priority: low |
| Status | needs-triage, blocked, ready, wontfix |
| Area | area: api, area: ui, area: infra |
| Community | good first issue, help wanted |
Run triage and planning on a board#
Use a GitHub Project with views for the backlog, the current iteration and a triage queue. The workflow is simple:
- New issues arrive with
needs-triage. - Someone triages on a rota: confirm, label, set priority, assign or close.
- Planned work is attached to a milestone that matches a release.
- Pull requests close their issue with a keyword (
Fixes #123), so the board moves by itself.
Close issues that go nowhere. A stale-issue workflow does it politely:
name: Stale issues
on:
schedule:
- cron: "30 1 * * *"
permissions:
issues: write
pull-requests: write
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9
with:
days-before-stale: 60
days-before-close: 14
stale-issue-label: stale
exempt-issue-labels: "priority: critical,security,blocked"
stale-issue-message: >
This issue has had no activity for 60 days. It will be closed in 14 days
unless there is an update.Backup, recovery and disaster recovery#
GitHub is a reliable service, but "the vendor is reliable" is not a backup strategy. Accidents (a deleted repository, a force-push), attacks (a compromised account) and outages all happen.
Know what git protects and what it does not#
Git is distributed, so every clone is a full copy of the code and history. But a lot of what makes a project work is not in git at all:
| Item | Protected by a git clone? |
|---|---|
| Code, branches, tags, commit history | Yes |
| Issues, pull requests and their discussions | No |
| Releases and release assets | No |
| Wiki (it is a separate git repository) | Only if you clone it too |
| Repository settings, rulesets, webhooks | No |
| Actions secrets and variables | No, and they cannot be exported |
| Projects, Discussions, Packages | No |
Set recovery goals first#
Two numbers shape everything. The RPO (recovery point objective) is how much work you can afford to lose, for example 24 hours. The RTO (recovery time objective) is how long you can afford to be without the repository, for example 4 hours. A nightly backup gives you a 24-hour RPO. If that is too long, back up more often.
Follow the 3-2-1 idea#
Keep three copies of your data, on two different kinds of storage, with one copy offsite and out of reach of the same account. For GitHub, that usually means the live repository, developers' clones, and a scheduled backup in a separate cloud account.
An automated backup you can adopt today#
This scheduled workflow mirrors repositories, exports issues and releases as JSON, and uploads them to S3. It authenticates to AWS with OIDC, so there is no stored AWS key. Run it from a dedicated backup repository, with a read-only token that can see the repositories you are backing up.
name: Backup repositories
on:
schedule:
- cron: "0 20 * * *" # nightly
workflow_dispatch:
permissions:
id-token: write
contents: read
jobs:
backup:
runs-on: ubuntu-latest
strategy:
matrix:
repo: [my-org/my-project, my-org/my-infra]
env:
GH_TOKEN: ${{ secrets.BACKUP_READ_TOKEN }}
REPO: ${{ matrix.repo }}
steps:
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ vars.BACKUP_ROLE_ARN }}
aws-region: ap-southeast-1
- name: Mirror the repository
run: |
AUTH=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 -w0)
echo "::add-mask::$AUTH"
git -c http.extraheader="AUTHORIZATION: basic $AUTH" \
clone --mirror "https://github.com/${REPO}.git" mirror.git
- name: Export issues, pull requests and releases
run: |
gh api --paginate "repos/${REPO}/issues?state=all&per_page=100" > issues.json
gh api --paginate "repos/${REPO}/releases?per_page=100" > releases.json
- name: Package and upload
run: |
STAMP=$(date -u +%Y-%m-%dT%H%M%SZ)
NAME="${REPO//\//_}"
tar -czf "${NAME}-${STAMP}.tar.gz" mirror.git issues.json releases.json
aws s3 cp "${NAME}-${STAMP}.tar.gz" "s3://my-backup-bucket/github/${NAME}/"Make the destination bucket trustworthy: enable versioning and Object Lock, lock down who can delete objects, and set a lifecycle rule to expire old backups. Ideally the bucket lives in a separate AWS account, so someone who compromises your GitHub organisation cannot also wipe your backups.
Two cautions. Scheduled workflows can be paused on inactive public repositories, so alert if no new backup appears in a day and a half. And a backup you have never restored is a hope, not a backup.
For full-fidelity organisation exports, look at GitHub's migration tooling and the GitHub Enterprise Importer, which can move issues and pull requests too.
Keep your settings as code#
Rulesets, labels, teams and repository settings are hard to rebuild from memory. Export rulesets as JSON and store them in a platform repository, or manage repositories with Terraform's GitHub provider or a settings-as-code tool. Then rebuilding after a disaster is an apply, not an archaeology project. Record where each secret comes from (a secret manager or password vault), because secrets cannot be pulled back out of GitHub.
Restoring from a mirror#
If a repository is lost, create an empty one and push your backup into it. Mirror clones include GitHub's read-only pull request references, which cannot be pushed back, so push branches and tags explicitly:
tar -xzf my-org_my-project-2026-10-12T200000Z.tar.gz
cd mirror.git
git remote set-url --push origin https://github.com/my-org/my-project-restored.git
git push --all origin
git push --tags originIssues and pull requests come back from the JSON export or a migration tool, and your settings from the code you saved.
Disaster scenarios and responses#
| Scenario | What to do | What prevents it |
|---|---|---|
| Force-push overwrote history | Recover the old commit from a clone or reflog, or from the latest mirror | Ruleset blocking non-fast-forward pushes |
| Branch deleted by mistake | Restore it from the closed pull request, or push it back from a clone | Ruleset blocking deletion, auto-delete only after merge |
| Whole repository deleted | Check for GitHub's deleted-repository restore window first, then restore from your mirror | Restricted admin rights, backups |
| Secret leaked | Rotate immediately, review access logs, then clean history if needed | Push protection, secret scanning |
| Account or token compromised | Revoke tokens and sessions, review the audit log for new keys, webhooks and changed workflows | 2FA, SSO, short-lived credentials |
| GitHub is down during an incident | Use a break-glass path: deploy from a mirror or a local clone, with the procedure written down and tested | Offsite mirror, documented runbook |
| Ransomware or a malicious insider | Restore from the locked backup in the separate account | Object Lock, separate account, least privilege |
Write the recovery steps down in a runbook inside the repository, and rehearse them at least once a quarter. The first time you follow the steps should not be during an emergency.
Documentation that people actually use#
Documentation rots when it is far from the code and hard to change. Keep it in the repository, review it like code, and give each document one job.
| File | Purpose |
|---|---|
README.md | What it is, why it exists, how to run it in five minutes |
CONTRIBUTING.md | Branching, commit style, how to run tests, review expectations |
CODE_OF_CONDUCT.md | Expected behaviour and how to report problems |
SECURITY.md | Supported versions and how to report vulnerabilities |
CHANGELOG.md | What changed in each release (generated, not hand-written) |
LICENSE | What others may do with the code |
docs/architecture/ | How the system fits together, with diagrams |
docs/adr/ | Architecture Decision Records: why we chose X over Y |
docs/runbooks/ | Step-by-step operational procedures: deploy, roll back, restore |
A good README answers these questions in order: what is this, how do I run it, how do I test it, how do I contribute, and where do I get help.
Architecture Decision Records deserve special mention. A short file per decision (context, decision, consequences) saves enormous time later, when someone asks why the team picked a database or a queue three years ago.
# ADR 0007: Use PostgreSQL for the orders service
- Status: Accepted
- Date: 2026-09-14
## Context
Orders need transactions and relational reporting. The team already operates PostgreSQL.
## Decision
We will use managed PostgreSQL for the orders service.
## Consequences
- Strong consistency and familiar tooling.
- We take on schema migrations and capacity planning.
- Revisit if write volume exceeds what a single primary can handle.Treat docs as code. Lint the Markdown and check links in CI (the lychee link checker has a ready-made action), and require documentation updates in the pull request checklist.
Standards that remove arguments#
The more rules are enforced by tools, the fewer are enforced by people in review comments. Decide them once, write them down, and automate them:
.editorconfigkeeps indentation, line endings and final newlines consistent across editors.- Formatter and linter (Prettier and ESLint, Black and Ruff,
gofmt, and so on) run in CI and, ideally, before each commit through a pre-commit hook. .gitattributesnormalises line endings (* text=auto eol=lf), which avoids the "every file changed" pull request caused by Windows line endings.- Pinned tool versions (
.nvmrc,.tool-versions, a devcontainer) mean "works on my machine" means something. - Lockfiles are committed and CI installs from them (
npm ci, notnpm install). - Commit and PR title linting keep history machine-readable.
- A Definition of Done the team agrees on, such as: tests pass, code reviewed, docs updated, no new high-severity alerts, deployed to staging.
Once the setup feels right, turn the repository into a template repository. New projects then start with every file, setting and workflow in place:
gh repo create my-org/new-service --template my-org/project-template --privateA maintenance rhythm#
Good repositories stay good because someone looks after them on a schedule:
| Cadence | Tasks |
|---|---|
| Weekly | Triage new issues, merge Dependabot pull requests, review open security alerts |
| Monthly | Review access and team membership, check backup freshness, look at failing or flaky workflows |
| Quarterly | Restore a backup as a drill, review rulesets and settings, rotate long-lived tokens, update ADRs and runbooks |
| Yearly | Review the branching and release process itself, audit third-party actions and integrations |
The setup checklist#
Use this as a runbook for any new repository:
- Set
mainas default, squash merge on, auto-delete branches on, wiki and unused features off. - Set Actions defaults: read-only token, approvals for outside contributors, an allow-list of actions.
- Create the branch ruleset and the tag ruleset. Keep the bypass list empty.
- Add
CODEOWNERS, the PR template and issue forms. - Create the
ci-gatejob and require it. - Enable secret scanning with push protection, code scanning, Dependabot alerts and security updates, and private vulnerability reporting.
- Add
dependabot.ymland the dependency review workflow. - Add
SECURITY.md,README.md,CONTRIBUTING.md,LICENSEand a docs folder with ADR and runbook starters. - Set up release automation and the release notes configuration.
- Schedule backups to a separate account, and write and rehearse the restore runbook.
- Add formatter, linter,
.editorconfig,.gitattributesand pre-commit hooks. - Put the whole thing in a template repository.
Wrapping up#
None of this is glamorous, and that is the point. A well-run repository is boring in the best way: changes flow in through the same path, risks are caught by machines before humans have to think about them, releases are routine, and a bad day has a rehearsed way out.
You do not have to do everything at once. Start with rulesets, a required CI check and secret scanning, since those give the biggest return. Then add the rest as the project grows. When you are ready to organise the files and folders themselves, continue with A Repository That Explains Itself: The Ideal GitHub Project Structure for DevOps Teams.
Related reading
A Repository That Explains Itself: The Ideal GitHub Project Structure for DevOps Teams
A guided tour of a DevOps-ready GitHub repository: root files, the .github folder, source and tests, docs, infrastructure, scripts, monorepo layouts and starter configs you can copy.
GitHubDevOpsProject StructureBest Practices
15 min readFrom Commit to Two Regions: A Multi-Region CI/CD Pipeline with AWS CodePipeline and CodeDeploy
Build a CI/CD pipeline on AWS DevOps tools: GitHub triggers CodePipeline, CodeDeploy ships to EC2 in two Regions, with a manual approval gate and an automated Lambda readiness check.
AWSCI/CDCodePipelineCodeDeploy
14 min readGoodbye Access Keys: Connecting GitHub Actions to AWS with OIDC
Replace long-lived AWS keys in GitHub secrets with short-lived OIDC credentials. IAM setup, trust policies, a working workflow, Terraform and a troubleshooting guide.
AWSGitHub ActionsOIDCIAM
9 min read