Git and GitHub for regulated teams
Choose a branching strategy, protect main with rulesets, route reviews with CODEOWNERS and signed commits, and turn every merge into audit evidence a bank's change board will accept.
Assumes: Git 2.4x · GitHub.com rulesets and CODEOWNERS · .NET 10 LTS (file-based apps) · Terraform GitHub provider 6.x · AWS CLI v2 (CodeCommit) · Region us-east-1. Verified against official sources on 2026-11-18.
Learning objectives
By the end of this lesson you can:
- Compare trunk-based development, GitHub Flow and GitFlow, and choose one for a bank team that ships an API weekly and must hot-fix within hours.
- Protect
mainwith a repository ruleset: required pull requests, approvals from someone other than the author, code-owner review, required status checks, signed commits, linear history and no force pushes. - Write a CODEOWNERS file that routes pipeline, IAM and release-rule changes to the right teams.
- Explain how branch protection, reviews and CI checks add up to segregation of duties, and what evidence each one leaves behind.
- Map Azure Repos branch policies to GitHub rulesets and to AWS CodeCommit approval rule templates.
- Enforce a commit-message convention (ticket references) with a small .NET 10 tool that runs in CI.
Prerequisites
- Module 9 overview — read the "How the pieces fit" diagram first.
- Federation and segregation of duties — the control idea this lesson implements in Git.
- Tools: Git, a GitHub account (a public repository keeps every feature in this lesson free), the GitHub CLI (
gh), optionally the .NET 10 SDK or Docker.
Why this matters in banking
Picture an incident review at Harbourline Bank. A change to the Payments Service rounded foreign-exchange amounts the wrong way for a few hours, and some customers were charged a few pence too much. The regulator's first questions are not about the bug. They are:
- Who wrote the change, and who reviewed it?
- Was the reviewer independent of the author?
- Which tests ran, and did they pass?
- Could anyone have changed the code after it was reviewed?
If the answers are "the developer pushed straight to main", "nobody", "we're not sure" and "yes", the incident becomes a control failure, and control failures are what produce findings, remediation programmes and, in serious cases, fines. If the answers come straight out of the repository — a pull request, two approvals from code owners, green required checks, signed commits and a ruleset that blocks force pushes — the conversation is about the bug, not about whether the bank is in control of its software.
Git hosting is therefore not just a developer convenience. In a bank it is the first change-management control, and the evidence it produces is the foundation for everything later in this module: pipelines, approvals and release records all point back to a reviewed commit.
The idea in plain language
Git stores every version of your code as a chain of commits. A branch is a movable label pointing at one commit. Developers make changes on their own branch, then ask for them to be merged into the shared branch (main). On GitHub the request to merge is a pull request (PR): a page that shows the diff, the discussion, the reviews and the results of automated checks.
A ruleset (or the older "branch protection rule") is a set of conditions GitHub enforces before anyone can change a protected branch. Typical conditions are "only through a pull request", "at least one approval", "the CI workflow must pass" and "no force pushes". A CODEOWNERS file says which people or teams own which paths, so that a change to, say, the IAM policies cannot merge without a review from the IAM owners.
Analogy: a bank's payment-release process uses four-eyes: one clerk prepares a payment, a second authorises it, and the system will not release it otherwise. A protected branch is four-eyes for code. The PR is the prepared payment, the approval is the second pair of eyes, the required checks are the automated sanctions and limit checks, and the ruleset is the system rule that stops anyone releasing a payment on their own.
Three branching strategies
| Strategy | How it works | Good for | Watch out for |
|---|---|---|---|
| Trunk-based development | Everyone merges small changes into main at least daily. Unfinished features hide behind feature flags. Releases are cut from main (often as tags). | Teams with strong automated tests who deploy often. Works best with this module's pipelines. | Needs discipline: small PRs, fast reviews, feature flags. |
| GitHub Flow | Short-lived feature branch → PR → merge to main → deploy. A light form of trunk-based. | Most API teams. The default in this module. | Long-lived feature branches creep back in if PRs are big. |
| GitFlow | develop plus main, with feature/*, release/* and hotfix/* branches merged back and forth. | Products shipped as versioned packages with long support (on-premises software). | Many merges, frequent conflicts, slow feedback. Its author now recommends simpler flows for continuously delivered software. |
For Harbourline's Accounts API — a service deployed by a pipeline, weekly or more often — the recommendation is GitHub Flow with release tags: short-lived branches, PRs into a protected main, and a tag such as v1.4.0 marking what was released. When a hotfix is needed for an older release still running in production, create a short-lived hotfix/1.4.1 branch from the tag, fix, PR, tag, and merge the fix back into main.
What problem GitHub (and AWS CodeCommit) solve
GitHub hosts the repository and enforces rules around it: who may push, what must happen before a merge, and who must review which files. It records each event (pushes, reviews, merges, rule bypasses) so that you can reconstruct the history later. Most banks that run on AWS use GitHub or GitLab for source control.
AWS also offers AWS CodeCommit, a private Git service inside your AWS account that uses IAM for access. CodeCommit was closed to new customers from July 2024 but returned to full general availability on 2025-11-24; the module's service availability notes explain this. Its equivalents of branch protection are approval rules and approval rule templates (for example "two approvals from members of this IAM role pool"), and IAM policies that deny codecommit:GitPush to main. It is a reasonable choice when policy says source code must stay inside AWS accounts. It has fewer collaboration features than GitHub, and this module uses GitHub by default.
Honest limitations:
- Plan gates. On GitHub Free, rulesets, protected branches and CODEOWNERS enforcement work for public repositories. Private repositories need GitHub Pro, Team or Enterprise for most of them (check GitHub's current plan pages before you rely on them for a private bank repository).
- Admins can bypass rules unless you take bypass rights away. A ruleset's bypass list is itself a control that auditors will review.
- A review is only as good as the reviewer. Rules prove that someone else looked; they do not prove the change was good. That is why tests, scanning and threat modelling sit alongside.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | GitHub / AWS equivalent | What's different |
|---|---|---|
| Azure Repos | GitHub repositories, or AWS CodeCommit | GitHub is the de facto default; CodeCommit is IAM-native |
| Branch policies: "Require a minimum number of reviewers" | Ruleset rule Require a pull request before merging with required approvals | GitHub adds "require approval of the most recent reviewable push" (someone other than the last pusher approves) |
| "Prohibit the most recent pusher from approving their own changes" | Require approval of the most recent reviewable push | Same intent: the person who pushed last cannot be the only approver |
| "Automatically included reviewers" by path | CODEOWNERS file + "Require review from Code Owners" | Stored in the repository, so changes to ownership are themselves reviewed |
| Build validation policy | Require status checks to pass | Name the exact check (job) that must be green |
| "Check for linked work items" | Ticket reference convention enforced by a CI check (this lesson's tool), or GitHub-to-Jira integration | Not a built-in rule; you enforce it with a required check |
| Branch security: deny "Force push" | Ruleset rules Block force pushes and Restrict deletions | Rulesets can target many branches by pattern and be set across an organisation |
| Azure DevOps audit log | GitHub audit log (organisation), repository rule insights | Enterprise plans can stream the audit log to S3 or a SIEM |
| — | CodeCommit approval rule templates | Pools of approvers defined by IAM ARNs; attach templates to repositories |
Architecture
Security-boundary view
- Who can write to
main: nobody directly. Only the merge button, and only when the ruleset is satisfied. - Who can change the rules: repository or organisation admins. Keep that group small, use organisation-level rulesets so a repository admin cannot quietly weaken them, and review the bypass list.
- Who can change ownership: anyone who can merge a PR that edits
CODEOWNERS— soCODEOWNERSshould own itself (/.github/CODEOWNERS @platform-team). - Where evidence lives: pull requests (diff, reviews, checks, merge commit), the audit log, and the tag that the release pipeline builds.
Step-by-step implementation
Choose the strategy and write it down
Write a one-page CONTRIBUTING.md: GitHub Flow, branch names feature/<ticket>-<short-name> and hotfix/<version>, PRs should be small (a reviewer can read them in 20 minutes), every commit references a ticket, releases are tags vMAJOR.MINOR.PATCH. Auditors like to see that the process exists on paper and that the tooling enforces the same thing.
Add CODEOWNERS
Create .github/CODEOWNERS. Order matters: the last matching pattern wins, so put the catch-all first and the specific paths after it. The lab file labs/m09-delivery-pipeline/.github/CODEOWNERS is a complete example: the pipeline (/.github/) needs platform engineering and application security; IAM policies (/policies/) need application security and the cloud IAM team; the release rules need change management.
Create a ruleset for main
Settings → Rules → Rulesets → New ruleset → New branch ruleset. Name it protect-main, enforcement Active, target Default branch. Turn on:
- Restrict deletions and Block force pushes.
- Require linear history (squash or rebase merges only — each PR becomes one readable commit).
- Require signed commits.
- Require a pull request before merging with 1 (or 2) required approvals, Dismiss stale pull request approvals when new commits are pushed, Require review from Code Owners, Require approval of the most recent reviewable push, and Require conversation resolution before merging.
- Require status checks to pass, adding the exact job names from your workflows (for the lab:
Build and unit/integration tests,Container image builds,Trust policies are safe,Secrets scan (full history)). Tick Require branches to be up to date before merging for small teams; use a merge queue for busy ones.
Leave the bypass list empty. If your bank needs a break-glass path, add one named team and document how its use is reviewed.
Sign commits
Configure Git to sign with an SSH key you already use for GitHub (simpler than GPG on Windows), upload the same key to GitHub as a signing key, and turn on vigilant mode in your GitHub settings so unsigned commits under your name show as "Unverified". Commits made by the merge button are signed by GitHub.
Enforce the commit-message convention
Add the ticket-reference checker from the Complete code section as a CI job, then add that job to the ruleset's required checks. Now "every change references a ticket" is enforced, not hoped for.
Test the rules like an attacker would
Try to git push origin main directly (rejected), approve your own PR (not allowed), push a new commit after approval (approval dismissed), edit policies/trust-deploy-prod.json without an AppSec review (blocked). Screenshot or export each refusal: this is your evidence that the control works.
AWS Console instructions
GitHub is configured in its own web interface (above). For AWS CodeCommit in the console:
- Console → CodeCommit → Approval rule templates → Create template. Name
two-reviewers-not-author, approvals needed 2, approval pool members: the ARN pattern of your reviewers' IAM Identity Center role, for examplearn:aws:sts::111122223333:assumed-role/AWSReservedSSO_Reviewer_*/*. Destination references:refs/heads/main. - Associated repositories: choose the repository. New pull requests into
mainnow need two approvals from the pool. - Console → IAM → Policies: attach a policy to developer roles that denies
codecommit:GitPush,codecommit:DeleteBranch,codecommit:PutFileandcodecommit:MergeBranchesBy*whencodecommit:Referencesisrefs/heads/main(the CLI section shows the JSON).
AWS CLI
# --- GitHub (gh CLI): inspect what actually protects main --------------------------------------
# List rulesets that apply to the default branch (works for public repos on any plan)
gh api repos/OWNER/REPO/rules/branches/main --jq '.[].type'
# Show recent rule evaluations (bypasses and failures are audit evidence)
gh api "repos/OWNER/REPO/rulesets/rule-suites?ref=refs/heads/main" --jq '.[] | {actor: .actor_name, result, pushed_at}'
# --- AWS CodeCommit: approval rule template ----------------------------------------------------
# Two approvals from the reviewer pool for any PR into main
aws codecommit create-approval-rule-template \
--approval-rule-template-name two-reviewers-not-author \
--approval-rule-template-description "Two approvals from the reviewer role, PRs into main" \
--approval-rule-template-content '{"Version":"2018-11-08","DestinationReferences":["refs/heads/main"],"Statements":[{"Type":"Approvers","NumberOfApprovalsNeeded":2,"ApprovalPoolMembers":["arn:aws:sts::111122223333:assumed-role/AWSReservedSSO_Reviewer_*/*"]}]}' \
--profile learn-sandbox --region us-east-1
# Attach the template to a repository
aws codecommit associate-approval-rule-template-with-repository \
--approval-rule-template-name two-reviewers-not-author \
--repository-name hl-m09-accounts-api \
--profile learn-sandbox --region us-east-1An IAM policy that stops developers pushing directly to main in CodeCommit:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DenyDirectChangesToMain",
"Effect": "Deny",
"Action": [
"codecommit:GitPush",
"codecommit:DeleteBranch",
"codecommit:PutFile",
"codecommit:MergeBranchesByFastForward",
"codecommit:MergeBranchesBySquash",
"codecommit:MergeBranchesByThreeWay"
],
"Resource": "arn:aws:codecommit:us-east-1:111122223333:hl-m09-accounts-api",
"Condition": {
"StringEqualsIfExists": { "codecommit:References": ["refs/heads/main"] },
"Null": { "codecommit:References": "false" }
}
}
]
}Infrastructure as Code
Rulesets clicked together in a web page drift. Treat them as code, reviewed like everything else.
terraform {
required_providers {
github = {
source = "integrations/github"
version = "~> 6.0" # ⚠ VERIFY the current major before use
}
}
}
# Authenticates with a GitHub App or a fine-grained token supplied by the pipeline,
# never a token committed to the repository.
provider "github" {
owner = "harbourline-learn"
}
resource "github_repository_ruleset" "protect_main" {
name = "protect-main"
repository = "accounts-api"
target = "branch"
enforcement = "active"
conditions {
ref_name {
include = ["~DEFAULT_BRANCH"]
exclude = []
}
}
rules {
deletion = true
non_fast_forward = true # block force pushes
required_linear_history = true
required_signatures = true
pull_request {
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
}
required_status_checks {
strict_required_status_checks_policy = true
required_check {
context = "Build and unit/integration tests"
}
required_check {
context = "Trust policies are safe"
}
required_check {
context = "Secrets scan (full history)"
}
}
}
}Complete code
A .NET 10 file-based app (a single .cs file you run with dotnet run) that checks every commit in a pull request references a ticket and is not a "fixup" left behind. It runs in CI and becomes a required status check.
// Usage: dotnet run tools/check-commits.cs -- <base-sha> <head-sha>
// Exit 0 = all commits OK, 1 = at least one problem, 2 = usage error.
using System.Diagnostics;
using System.Text.RegularExpressions;
if (args.Length != 2)
{
Console.Error.WriteLine("Usage: check-commits <base-sha> <head-sha>");
return 2;
}
// Ticket keys such as CHG-104233 (change) or ACC-512 (Jira project "ACC"). Adjust to your tracker.
var ticket = new Regex(@"\b(CHG|ACC|PAY)-\d{1,7}\b", RegexOptions.CultureInvariant);
var forbiddenPrefixes = new[] { "fixup!", "squash!", "wip", "WIP" };
var log = Git("log", "--format=%H%x1f%an%x1f%s", $"{args[0]}..{args[1]}");
var problems = 0;
foreach (var line in log.Split('\n', StringSplitOptions.RemoveEmptyEntries))
{
var parts = line.Split('\x1f');
var (sha, author, subject) = (parts[0][..12], parts[1], parts[2]);
if (forbiddenPrefixes.Any(p => subject.StartsWith(p, StringComparison.Ordinal)))
{
Console.WriteLine($"FAIL {sha} ({author}): work-in-progress commit '{subject}' — squash it before merging.");
problems++;
}
else if (!ticket.IsMatch(subject))
{
Console.WriteLine($"FAIL {sha} ({author}): '{subject}' has no ticket reference (e.g. 'ACC-512: add statement paging').");
problems++;
}
else
{
Console.WriteLine($"ok {sha} {subject}");
}
}
Console.WriteLine(problems == 0 ? "All commits reference a ticket." : $"{problems} commit(s) need fixing.");
return problems == 0 ? 0 : 1;
static string Git(params string[] arguments)
{
var psi = new ProcessStartInfo("git") { RedirectStandardOutput = true, RedirectStandardError = true };
foreach (var a in arguments)
{
psi.ArgumentList.Add(a);
}
using var p = Process.Start(psi) ?? throw new InvalidOperationException("git not found");
var output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
if (p.ExitCode != 0)
{
throw new InvalidOperationException(p.StandardError.ReadToEnd());
}
return output;
}The workflow job that runs it on every pull request:
name: commit-policy
on:
pull_request:
branches: [main]
permissions:
contents: read
jobs:
commits:
name: Commits reference a ticket
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0 # we need the PR's commits, not just the merge result
persist-credentials: false
- uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0
with:
dotnet-version: "10.0.x"
- name: Check commit messages
run: dotnet run tools/check-commits.cs -- ${{ github.event.pull_request.base.sha }} ${{ github.event.pull_request.head.sha }}Code explained line by line
if (args.Length != 2)— the tool takes the base and head SHAs of the pull request. Exit code2means "you called me wrongly", which CI shows differently from a policy failure (1).new Regex(@"\b(CHG|ACC|PAY)-\d{1,7}\b", ...)— the ticket pattern.\bmakes sureXACC-1does not count.CultureInvariantavoids surprises on machines with unusual locales.forbiddenPrefixes—git commit --fixupcreatesfixup!commits meant to be squashed. If they reachmainwith linear history on, history becomes noisy and harder to audit.Git("log", "--format=%H%x1f%an%x1f%s", $"{args[0]}..{args[1]}")— lists commits reachable from the head but not from the base: exactly the PR's commits.%x1f(unit separator) splits fields safely even when a subject contains spaces or pipes.parts[0][..12]— the first 12 characters of the SHA, enough to be unique in practice and readable in logs.- The three branches print ok or FAIL with the author and the reason. A reviewer can read the CI log and know exactly what to change.
return problems == 0 ? 0 : 1;— a non-zero exit fails the job, and because the job is a required status check, the merge button stays disabled.Git(...)usesArgumentListrather than one concatenated string, so a SHA (or a malicious branch name) cannot inject extra shell arguments.- In the workflow,
fetch-depth: 0fetches full history; with the default shallow clone the base SHA would be missing andgit logwould fail. - The job
name:("Commits reference a ticket") is the string you add to the ruleset's required checks.
Security considerations
⚠ Learning shortcut — not for production
In this lesson you may protect a personal public repository with one required approval and act as both author (on one account) and reviewer (on a second account). That proves the mechanics but not independence. In production, approvals must come from a different person in a defined reviewer group, rulesets should be set at the organisation level so repository admins cannot weaken them, the bypass list should be empty or limited to a documented break-glass team, and the organisation audit log should be streamed to the bank's log archive (Module 5's CloudTrail lesson shows the AWS side).
- Workflow files are code that runs with your secrets. Put
/.github/under CODEOWNERS with the platform and security teams. A PR that edits a workflow to print secrets must not merge on a developer's approval alone. pull_request_targetis dangerous. It runs with the base repository's secrets on code from a fork. Avoid it unless you understand the risk; this module never uses it.- Signed commits prove who committed, not what they meant. Combine signing with review.
- Don't store secrets in the repository, even briefly. History keeps them. The security workflow in Lab 9.3 scans full history for that reason.
- Personal access tokens used to automate GitHub (for example by Terraform) should be fine-grained, short-lived and scoped to the repositories they manage — or replaced by a GitHub App.
Banking use case
Harbourline's Accounts API team has six developers. Their change policy, agreed with risk, says: every production change has a ticket; code is reviewed by someone other than the author; IAM and pipeline changes are reviewed by security; and the bank can show the full history of any release for seven years.
The team implements it like this:
| Policy requirement | Git/GitHub control | Evidence produced |
|---|---|---|
| Every change has a ticket | check-commits.cs as a required check | CI log per PR; ticket keys in commit messages |
| Independent review | Ruleset: 1 approval, last-push approval, dismiss stale approvals | PR review history |
| Security reviews IAM and pipeline changes | CODEOWNERS for /policies/, /.github/, /infra/ | Code-owner approval on the PR |
| Code cannot change after review | Dismiss stale approvals; block force pushes; linear history | Ruleset configuration (as Terraform) and rule insights |
| Released code is identifiable | Release tag on the merge commit; pipeline builds only from tags/main | Tag → commit → PR chain |
| History kept for years | Audit log streamed to an S3 bucket with Object Lock | Immutable archive |
A later lesson in this module (release management and audit evidence) turns these pieces into a release-evidence pack.
Common mistakes
- Protecting
mainbut leaving admins able to bypass → "temporary" bypasses become normal → keep the bypass list empty and review rule-suite results. - CODEOWNERS ordered wrongly → the catch-all at the bottom overrides specific owners → specific paths go after the catch-all, because the last match wins.
- Requiring a status check by a name that never runs → the PR waits forever ("Expected — waiting for status") → copy the exact job name from a completed run.
- Huge pull requests → reviewers skim and approve → limit PR size by convention and use feature flags to merge unfinished work safely.
- Long-lived release branches in a continuously delivered service → fixes land in one branch and not the other → prefer tags plus short-lived hotfix branches.
- Treating "approved" as "tested" → required checks are what prove tests ran; reviews prove a human looked.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Merge button says "Required statuses must pass" but all checks are green | Required check name does not match any job (renamed job, or a matrix job name) | Update the ruleset with the exact job name shown on the PR |
| "Review required" even after a teammate approved | Code-owner review required for a path they don't own, or approval was dismissed by a new push | Check the PR's "Code owners" panel; re-request review after the last push |
remote: error: GH013: Repository rule violations found on push | Pushing directly to a protected branch, an unsigned commit, or a force push | Push to a branch and open a PR; sign the commits; never force-push main |
| Commits show "Unverified" | Signing key not uploaded as a signing key, or email mismatch | Add the key under SSH and GPG keys as Signing key; use a verified email |
| CODEOWNERS file ignored | Wrong location or syntax error | Use .github/CODEOWNERS, CODEOWNERS or docs/CODEOWNERS; GitHub shows syntax errors on the file page |
| CodeCommit PR can be merged without approvals | Template not associated, or destination reference doesn't match | aws codecommit list-associated-approval-rule-templates-for-repository and check refs/heads/main |
Cost and cleanup
Cost: free. Public GitHub repositories get rulesets, CODEOWNERS and Actions at no charge. AWS CodeCommit is optional here; check current pricing before creating repositories (there is a per-active-user charge beyond the free allowance ⚠ VERIFY current CodeCommit free tier).
Cleanup:
# Remove the CodeCommit template and repository if you created them
aws codecommit disassociate-approval-rule-template-from-repository \
--approval-rule-template-name two-reviewers-not-author --repository-name hl-m09-accounts-api \
--profile learn-sandbox --region us-east-1
aws codecommit delete-approval-rule-template --approval-rule-template-name two-reviewers-not-author \
--profile learn-sandbox --region us-east-1
aws codecommit delete-repository --repository-name hl-m09-accounts-api --profile learn-sandbox --region us-east-1
# Check nothing tagged for the lab remains
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab \
--profile learn-sandbox --region us-east-1 --query "ResourceTagMappingList[].ResourceARN"On GitHub, keep the ruleset: the rest of the module relies on it.
Exercises
- 🟢 Guided: create a public repository from
labs/m09-delivery-pipeline, add theprotect-mainruleset exactly as in the steps, then try each "attack" in the last step and record the refusal message for each. - 🟡 Challenge: express the same ruleset as Terraform with the GitHub provider, import the hand-made ruleset into state, and show
terraform planreports no changes. - 🔴 Live problem: Ticket INC-2291: "A developer merged a change to
.github/workflows/release.ymlon Friday night that removed the Trivy step. Two approvals were recorded. Security asks how this passed." Investigate what combination of settings allowed it and propose the smallest set of changes that would have stopped it.
Assignment
Write CONTRIBUTING.md and .github/CODEOWNERS for a repository holding the Payments Service, its CDK infrastructure and its pipeline. Add a one-page "Source control controls" table mapping each policy requirement to a control and to the evidence it produces (like the banking use-case table above). Commit both to your portfolio repository.
Solutions
Expected refusals: a direct push is rejected with GH013 naming the "Changes must be made through a pull request" rule; you cannot approve your own PR (the button is disabled for authors); after you push another commit the earlier approval shows as dismissed; a PR touching /policies/ shows "Review required — waiting on code owner review from appsec". Recording the messages matters because evidence that a control operates is what an auditor tests, not the configuration screenshot alone.
Write the github_repository_ruleset resource from the IaC section, then run terraform import github_repository_ruleset.protect_main accounts-api:<ruleset-id> (the ID is in the ruleset's URL or gh api repos/OWNER/REPO/rulesets). Adjust attributes until terraform plan is clean. The point: future changes to protection now go through a PR with a plan output, so weakening a rule is visible and reviewed.
Likely causes, in order: (1) /.github/ was not in CODEOWNERS (or a later catch-all line overrode it), so any two developers could approve; (2) "Require review from Code Owners" was off; (3) the approvals happened before a later push and "dismiss stale approvals" was off, so the step was removed after review; (4) an admin bypassed. Fix: CODEOWNERS entry /.github/ @platform-engineering @appsec placed after the catch-all, require code-owner review, dismiss stale approvals, require last-push approval, empty bypass list, and an organisation-level ruleset. Also add a required check that fails if the security workflow is missing a Trivy step (policy as code on the workflow itself).
Knowledge check
Answer: @appsec. The last matching pattern wins, which is why specific paths go below the catch-all. If the order were reversed, @devs would own everything.
Answer: the person who pushed the last commit approving the PR in a way that counts. Without it, a reviewer could push a change to someone else's PR and approve it themselves, defeating four-eyes. It matches Azure Repos' "prohibit the most recent pusher from approving".
Answer: short-lived branches mean small, fast reviews, fewer merge conflicts and a single source of truth (main) for what can be deployed. GitFlow's long-lived develop and release branches suit versioned products with parallel supported releases; for a service deployed weekly they add merges and delay feedback.
Answer: no. Signing proves which key (and so which person) created the commit and that it wasn't altered. Review is a separate control (required approvals, code owners). You need both.
Answer: an approval rule template with NumberOfApprovalsNeeded: 2, a pool of approver ARNs and destination reference refs/heads/main, associated with the repository — combined with an IAM deny on direct pushes to main.
Interview questions
- "How do you enforce four-eyes on code changes in a regulated team?" — Protected
main(ruleset), PR required with at least one approval from someone other than the author and the last pusher, stale approvals dismissed on new commits, code-owner review for sensitive paths, required CI checks, no force pushes, empty bypass list, and the audit log kept. - "Which branching strategy would you pick and why?" — GitHub Flow or trunk-based with feature flags and release tags for services; GitFlow only for products with several supported versions at once. Explain the trade-off in feedback speed and merge cost.
- "Who should own the CI/CD workflow files?" — Platform and security, via CODEOWNERS, because workflows run with deployment credentials. A change that weakens a scan or widens a role must be reviewed by people accountable for those controls.
- "How would you show an auditor that a release was reviewed?" — Follow the chain: release tag → merge commit → PR → reviews, required checks and their logs → ruleset configuration in Terraform → audit log showing no bypass.
Certification practice
A company stores application code in AWS CodeCommit. Security requires that every pull request into main is approved by at least two members of the security-review group before it can be merged, and developers must not be able to push directly to main. Which combination of steps meets these requirements? (Choose TWO.)
A. Create an approval rule template requiring two approvals from a pool containing the security-review role, with destination reference refs/heads/main, and associate it with the repository.
B. Create an Amazon EventBridge rule that reverts commits pushed to main.
C. Attach an IAM policy to developer roles that denies codecommit:GitPush and the merge actions when codecommit:References is refs/heads/main.
D. Enable AWS CloudTrail data events for CodeCommit.
E. Configure a CodeBuild project to run on every push to main.
Answer: A and C. A enforces the approvals on PRs; C prevents bypassing the PR process. B reacts after the fact and races with developers. D records activity but prevents nothing. E tests code but doesn't enforce review.
A team deploys an API several times a week from main. They currently use GitFlow and spend hours resolving merge conflicts between develop, release/* and main; hotfixes take two days. What change best reduces lead time while keeping a record of what was released?
A. Add a second long-lived staging branch.
B. Move to short-lived feature branches merged into a protected main, mark releases with tags, and create short-lived hotfix branches from the release tag when needed.
C. Allow developers to push directly to main to skip pull requests.
D. Release only once a month to reduce merges.
Answer: B. Trunk-based/GitHub Flow with tags shortens feedback and keeps traceability. A adds merges. C removes the review control. D increases batch size and risk.
A developer must ensure every container image deployed to Amazon ECS can be traced back to the exact source commit and its pull request. Which approach is MOST reliable?
A. Tag images with latest and keep a wiki page of deployments.
B. Tag images with the full Git commit SHA (and a semantic version), deploy by image digest, and build only from commits merged through pull requests on a protected branch.
C. Include the build date in the image tag.
D. Store the source code inside the image.
Answer: B. The commit SHA links image → commit → PR; the digest guarantees the deployed bytes; branch protection guarantees the commit was reviewed. A loses traceability as latest moves. C is not unique to a commit. D bloats the image and still doesn't prove review.
Completion checklist
- I can explain GitHub Flow, trunk-based development and GitFlow, and when to use each
- My repository's
mainhas a ruleset with PRs, approvals, code-owner review, required checks, signed commits and no force pushes - CODEOWNERS routes
/.github/,/policies/and/infra/to the right teams, in the right order - The commit-message check runs as a required status check
- I recorded evidence that each rule actually blocks what it should
Key takeaways
- In a bank, source control is the first change-management control; its records are audit evidence.
- Prefer short-lived branches into a protected
mainwith release tags; keep GitFlow for multi-version products. - A ruleset makes four-eyes real: PR required, independent and last-push approval, stale approvals dismissed, code owners, required checks, signed commits, no force pushes, no bypass.
- CODEOWNERS (last match wins) routes sensitive changes — workflows, IAM, release rules — to accountable teams.
- Manage rulesets as code and test them like an attacker; CodeCommit offers approval rule templates plus IAM denies when code must stay in AWS.
Further reading
Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.
Module 9: DevOps & CI/CD
Move from Azure DevOps pipelines to AWS-ready delivery: GitHub Actions with OIDC (no stored AWS keys) or CodePipeline, CodeBuild and CodeDeploy. You build a pipeline that tests, scans and deploys an ASP.NET Core API with blue/green releases, production approval and automatic rollback, producing the audit evidence banks require.
CI/CD concepts on AWS: stages, artefacts, environments and where each tool fits
Learn the vocabulary and the shape of a delivery pipeline (build once, promote the same artefact, gate each stage), map every stage to GitHub Actions or the AWS developer tools, and choose between them with a decision rule you can defend to an architecture board.