Git Hour 4: Towards a Hosted Platform (AWS CodeCommit and GitLab)

The same myapp repository is replaced by two platforms: AWS and GitLab: how to do certification, how to protect main, how to approve MR/PR, and how to mirror and migrate the repository across platforms
Git 2.56AWS CodeCommit (2025-11 Back to GA)AWS CodeConnectionsGitLab 19.5Verified according to official documents · 2026-11-15
overall learning objectives
  • Make it clear AWS CodeCommitStop accepting new customers from 2024-07 to2025-11-24 Return to general availability (GA)The process and current situation, and know where to check the status of roadmap projects such as Git LFS; be able to distinguish between GitLab.com (SaaS), GitLab Dedicated and GitLab Self-Managed.
  • Choose the correct authentication method for CodeCommit:Federation/temporary credentials → git-remote-codecommit (AWS recommended);The simplest for IAM users isHTTPS Git credentials;SSH keys and AWS CLI Credential Assistant as alternatives. Can you explain how to use git-remote-codecommit with IAM temporary credentials?SigV4 signatureprocess.
  • Use on CodeCommitIAM Conditional Policy (codecommit:References + Null)To refuse to push to main, useApproval rule templateRequire PR approval, connect to SNS/Lambda with notification rules and triggers.
  • use AWS CodeConnections(formerly CodeStar Connections) connects GitHub/GitLab repositories to services such as CodePipeline, understandPENDING → AVAILABLEStatus andUseConnection/PassConnectionpermissions.
  • Configure on GitLabprotected branch(Allowed to merge / Allowed to push and merge)、Merge Request、Approval Rules and CODEOWNERS、Push rules, and be clear about which features require Premium/Ultimate.
  • buildGitLab → CodeCommit push image, can diagnose issues such as 403, credential assistant conflicts, protected branch rejections, large file and LFS differences, and complete inter-platform migrations.

1-hour time allocation table

#timemodulecore contentanimation/interactionexperiment
0before classWarm-up and platform account preparationAWS account and IAM Identity Center, GitLab.com account, AWS CLI v2, git-remote-codecommit, glab; reuse the myapp practice repositoryEnvironmental self-check listaws sts get-caller-identity、glab auth status
100–05Git service positioning between AWS and GitLabCodeCommit will stop updating in 2024, resume GA and roadmap in 2025-11; GitLab SaaS / Dedicated / self-managed; package differencesCodeCommit Timeline + Platform SelectorCheck available areas and account status
205–13CodeCommit: Authentication with git-remote-codecommitFour connection methods and recommended order, IAM Identity Center configuration file, Git credentials, SSH,aws codecommit CLICore Animation: GRC uses temporary credentials for SigV4 signingClone and push myapp with SSO configuration file
313–21CodeCommit: branch protection, approval rules and notificationsIAM Deny + codecommit:References + Null;Approval rule template;Notification rule;TriggerIAM policy evaluatorRefuse to push main + 2 people approve PR
421–28CodeConnections: Connecting GitHub/GitLab to AWSSupported providers, PENDING handshake, host resources,UseConnection/PassConnection, condition keyconnection state machineCreate a GitLab connection and complete the handshake
528–37GitLab: Projects, Protected Branches, and MRGroups/projects/roles, protected branch options, MR merge methods,glab CLICore Animation: Protected branch rejects pushProtect main and merge with MR
637–44GitLab: Approval Rules, CODEOWNERS, and Push RulesApproval rules and settings, CODEOWNERS location and syntax, push rules and packagesMR Approval CalculatorCODEOWNERS + Push Rules (Premium Trial)
744–54Cross-platform mirroring and troubleshooting practicePush/Pull Mirrors, CodeCommit 403, Credential Assistant Violation, Protected Branch Rejection, Large Files and LFSMirror Sync Simulator + Interactive Troubleshooting TreeGitLab → CodeCommit push image
854–60Migration, costs and self-testingGitHub/Azure Repos ↔ GitLab/CodeCommit migration, CodeCommit billing, GitLab package, self-testcost calculatorgit push --mirrorMigrate in batches
—After classcheat sheet · Comprehensive experimentCodeCommit and GitLab dual platform protection + push image + verification + cleaningFinal exam 12 questionsComprehensive experiment

Knowledge Coverage Matrix Knowledge Coverage Matrix

target skillM1M2M3M4M5M6M7M8key commandsexperiment
Choose hosting platform and deployment form✓··✓···✓aws codecommit list-repositoriesM1
CodeCommit Authentication (GRC / Git Credentials / SSH)·✓····✓·git clone codecommit::REGION://PROFILE@REPOM2
CodeCommit branch protection and approval··✓···✓·create-approval-rule-templateM3 / Comprehensive Experiment
Notifications, triggers and events··✓·····put-repository-triggersM3
External repository access to AWS (CodeConnections)···✓···✓aws codeconnections create-connectionM4
GitLab protected branches and MR····✓✓✓·glab mr create、glab api protected_branchesM5 / Comprehensive Experiment
Approval rules, CODEOWNERS, push rules··✓··✓··glab api push_ruleM6
Cross-platform mirroring······✓✓glab api remote_mirrorsM7 / Comprehensive Experiment
Platform troubleshooting (403, credential conflict, push rejection, large files)·✓✓✓✓✓✓·GIT_TRACE=1、GIT_CURL_VERBOSE=1M7 Troubleshooting Tree
Migration and Cost Assessment✓······✓git push --mirrorM8

What’s excluded from this lesson (and where to learn it)

TopicWhy not in this lessonwhere to study
Azure Repos, GitHub (rule sets, GCM, merge queue)Belongs to the previous lessonLesson 3
CodePipeline / CodeBuild pipeline, GitLab CI/CD (.gitlab-ci.yml) detailsThis lesson only talks about Git-related capabilities on the platform, and ends with the assembly line.Lesson 5(Git in CI/CD) and subsequent independent platform courses
Branch strategy (GitFlow/trunk development), single repository architectureBelongs to the topic of architectureLesson 6
History rewritten (git filter-repo), remove leaked secretsIn-depth debuggingLesson 7 (This lesson only explains how to block on the platform side)
GitLab Runner, security scanning (SAST/DAST), GitLab DuoBeyond Git hosting itselfdocs.gitlab.com

How to use this courseware

10 tabs per module
Principles · Diagrams · Animations · Commands · Experiments · Production Examples · Troubleshooting · Tests · Voice · Videos. Let’s look at the “principles” and “animations” first, and then do the “experiments”. The animation of the M2 and M5 is the core of this lesson.
learning progress
Score ≥ 70% on the quiz or click "Mark this module complete" to count the progress and save it in this browser (it will be cleared after refreshing when local storage is disabled).
Chinese voice
The "Voice" tab uses the built-in Web Speech API (zh-CN) of the browser to read the explanation script; if there is no Chinese voice package, the explanation script can still be read or handed over to the TTS tool.
Version and status descriptionThe verification date of this lesson is 2026-11-15.CodeCommit: No more new customers will be accepted starting from 2024-07-25.2025-11-24 AWS announces restoration of full availability(User Guide document history is 2025-11-25), available in 29 regions, with the same price and 99.9% SLA; the roadmap announced at that time wasSupport Git LFS in Q1, 2026、Expanded to eu-south-2 and ca-west-1 from Q3 2026--As of the date of verification, in the Documentation History and Quotas page of the CodeCommit User GuideNoThese two online records will be treated as "not yet supported for LFS" in this lesson. Please refer to AWS What's New and User Guide.GitLab: The current version is 19.5 (2026-10-15), and a new version is released on the third Thursday of every month; the function package attribution (Free/Premium/Ultimate) is subject to the Tier mark at the top of each page of docs.gitlab.com.

Module 0 · Warm-up and platform account preparation (completed before class)

Prepare two AWS and GitLab.com accounts, four command line tools, and confirm that the myapp practice repository in Lesson 1 is available
Before class ≈ 15 minutesAWS CLI v2 · git-remote-codecommit · glab
Prerequisites
  • CompletedLesson 1(local~/git-lab/myapppractice repository) withLesson 3(Understand the general concepts of HTTPS Credential Assistant, PRs, and branch protection).
  • Host: Ubuntu 24.04 (Azure VM or WSL), macOS, or Windows (Git for Windows + Git Bash); Git ≥ 2.28 (2.56 recommended).
  • AWS account: CodeCommit has reopened to new customers; this lesson uses the areaca-central-1(Consistent with Docker class). Requires the ability to create IAM policies/roles (or assign permission sets in IAM Identity Center by an administrator).
  • GitLab.com account: The Free package can complete protected branches, MR, and push images; Approval rules, CODEOWNERS approval, and push rules require Premium/Ultimate (you can use the trial provided by GitLab, or just read without operating).

Fees, permissions and security tips (read first)

ProjectDosage for this lessoncostRequired permissions
CodeCommit2–3 test repositories, 1–2 active identitiesThe CodeCommit free tier is "valid for new and old customers on a long-term basis", and the first 5 active users are free (6 active users per month are billed at $1, see M8); this lesson is expected to$0AWSCodeCommitPowerUser(Exercise) + Create an IAM Policy (Admin)
IAM / IAM Identity Center1 permission set or role, 1 image-specific IAM userfreeIAM administrator or Identity Center administrator
CodeConnections1 connectionThe connection itself is not charged separately (services such as CodePipeline that use it are charged their own prices)codeconnections:*Create/handshake permissions in
SNS/Lambda (trigger)1 SNS topicWithin free tiersns:CreateTopicWait
GitLab.com1 group, 1–2 projectsFree; Premium features require trial or paymentGroup Owner/Project Maintainer
Safety tips① Do not use the AWS root user for experiments; ② This lesson will generateHTTPS Git credentials(long-term static password) vs.GitLab personal access token, the experiment must be canceled according to the last step of the comprehensive experiment; ③ There is a deliberately placed false secret in the practice repository historyFAKE_SECRET=...(Generated in Lesson 1), before pushing to the public platform, please confirm that the visibility of the repository isPrivate。

Step 1: Install/Check Tools

# Git (Ubuntu uses git-core PPA to get new versions)
sudo add-apt-repository -y ppa:git-core/ppa && sudo apt-get update && sudo apt-get install -y git
git --version

# AWS CLI v2 (Linux x86_64; see the official installation page for macOS/Windows)
curl -sSL "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o awscliv2.zip
unzip -q awscliv2.zip && sudo ./aws/install --update
aws --version

# git-remote-codecommit (Ubuntu 24.04 system Python is protected by PEP 668, install with pipx)
sudo apt-get install -y pipx && pipx ensurepath
pipx install git-remote-codecommit
command -v git-remote-codecommit

#glab (GitLab official CLI): macOS: brew install glab; Windows: winget install glab.glab
# Linux: Download the .deb from https://gitlab.com/gitlab-org/cli/-/releases, or brew install glab
glab --version
git version 2.56.0
aws-cli/2.x.x Python/3.x Linux/6.x exe/x86_64.ubuntu.24
/home/azureuser/.local/bin/git-remote-codecommit
glab 1.x.x (…)

Version numbers are examples.git-remote-codecommitmust be inPATHMedium: Git Encountercodecommit://At the beginning of the URL, it will go to PATH to find the URL namedgit-remote-codecommitexecutable file (Git's remote helper mechanism, see M2). AWS documentation requires it to work withAWS CLI v2Temporary credentials such as IAM Identity Center (SSO) and federated identities can be used.

Step 2: Configure an AWS identity (IAM Identity Center recommended)

aws configure sso --profile cc-dev
# SSO session name: lab
# SSO start URL: https://d-xxxxxxxxxx.awsapps.com/start
# SSO region: ca-central-1
# Select an account and permission set (such as CodeCommitDev with AWSCodeCommitPowerUser)
# CLI default client Region: ca-central-1
aws sso login --profile cc-dev
aws sts get-caller-identity --profile cc-dev
{
    "UserId": "AROAXXXXXXXXXXXXXXXXX:alice@example.com",
    "Account": "111122223333",
    "Arn": "arn:aws:sts::111122223333:assumed-role/AWSReservedSSO_CodeCommitDev_0123abcd/alice@example.com"
}

in ARNassumed-role/AWSReservedSSO_…It means you gotTemporary credentials for the role- This is exactly the scenario where HTTPS Git credentials cannot be used, but git-remote-codecommit can be used. If you do not have a personal account in Identity Center, you can create an IAM user andaws configure --profile cc-dev(access key), M2 compares the two.

Step 3: Log in to GitLab.com

glab auth login --hostname gitlab.com # Select browser login or paste personal access token (scope: api, write_repository)
glab auth status
gitlab.com
  ✓ Logged in to gitlab.com as alice (…/glab-cli/config.yml)
  ✓ Git operations for gitlab.com configured to use https protocol.
  ✓ Token: **************************

Step 4: Reuse or rebuild the myapp practice repository

All experiments in this lesson push the results generated in Lesson 1~/git-lab/myapp. If it has been deleted, please go back toLesson 1 Module 0Rerunbootstrap-git-lab.sh. Check:

cd ~/git-lab/myapp
git status -sb
git branch -a
git log --oneline --graph --all | head -15
git tag
Connection with previous lessonLesson 3 Pushed myapp to GitHub/Azure Repos (remote nameorigin/azure). Two new remotes are added to this lesson:gitlab with cc(CodeCommit), a local repository can have multiple remotes at the same time, which is also the basis for M7/M8 mirroring and migration.

Warm-up: Answer from memory (30 seconds)

Who is "entering the password" in Git's HTTPS push?

Git callsCredential Assistant(credential helper,git credential fillprotocol), the helper returns the username and password from the keychain/GCM/environment, which is then put into the HTTP Basic authentication header by libcurl. CodeCommit's AWS CLI Credential Helper and git-remote-codecommit both "dynamically generate passwords" at this level.

Is branch protection a Git feature?

No. Git itself has no concept of permissions; branch protection isServerin git-receive-packChecks to do when receiving ref updates (GitHub rulesets, GitLab protected branches, CodeCommit's IAM conditional policies).

Environmental self-check list

Module 1 · Git service positioning of AWS and GitLab

00:00 – 05:00 · CodeCommit is a “Git repository in an AWS account”, and GitLab is an “integrated DevSecOps platform” – different positioning and different selection criteria
5 minutesCodeCommit 2025-11 Restore GALFS still on the roadmap★★★★
learning objectives
  • Retelling the key points in CodeCommit: 2024-07-25 Stopping new customers → 2025-11-24 Resuming GA, as well as the roadmap (LFS, regional expansion) and verification methods announced at that time.
  • Distinguish between GitLab.com, GitLab Dedicated, and GitLab Self-Managed (CE/EE), and know the impact of Free / Premium / Ultimate on the functionality of this lesson.
  • Select the appropriate platform combination for the team based on the identity system, compliance, ecology and cost (such as "GitLab main repository + CodeCommit mirror").
Prerequisite knowledge:Lesson 3 General Concepts of Hosting Platforms.Importance:★★★★ (Migration costs for incorrect selection are high)

What: What are the two platforms?

AWS CodeCommitIt is an AWS-hosted private Git repository service: the repository belongs to an AWS account.area, identity and authorization are completely based onIAM(Users, roles, Identity Center permission sets), data is encrypted with KMS (customer-managed keys are supported from 2023-12), PRs, approval rules, notifications and triggers are provided. It has no Issues, Wiki, or built-in CI, and the pipeline is handed over to CodeBuild/CodePipeline.

GitLabIt is an integrated DevSecOps platform: in addition to the Git repository, there are Issues, MR, CI/CD, package and container image repositories, security scanning, etc. Identity is GitLab's own user vs.role(Guest, Planner, Reporter, Developer, Maintainer, Owner), pressGroup → Subgroup → Projectinheritance.

Why: CodeCommit’s “deactivation-resurrection” process

Dateeventwhat does it mean to you
2015-07-09CodeCommit User Guide first released—
2020-03-04Introducing git-remote-codecommit as the recommended method for federated/temporary credential accessThe heart of the M2
2023-12-21Support for customer managed KMS keysSelf-managed keys in compliance scenarios
2024-07-25'No longer open to new customers', existing customers can continue to use; AWS announces migration to other Git providers blogA large number of teams are beginning to move out to GitHub/GitLab
2025-11-24AWS DevOps Blog announces CodeCommitRestoration General Availability (GA), effective immediately; new customers can create repositorys again through the console, CLI, and API; 29 regions; prices and 99.9% SLA remain unchanged; customers who have moved out or are migrating can come back or pause the migrationCodeCommit becomes optional again during selection
2025-11-25User Guide Document History "now available to new customers"Official document caliber
2026 Q1 (Roadmap)Git LFS support("Most Anticipated Feature")As of 2026-11-15, there is no online record of the user guide, and it is designed as "not supported"
From Q3 2026 (Roadmap)Extended to eu-south-2 (Spain) and ca-west-1 (Calgary)As of the verification date, these two regions are not yet in the region list on the quota page.
How to verify it yourself① User Guide → Document history (docs.aws.amazon.com/codecommit/latest/userguide/history.html); ② Quota page Regions list; ③ AWS What's New search "CodeCommit"; ④ Pricing page. The blog says "plan" and the document history says "online".

How: Three deployment forms of GitLab

GitLab.com (SaaS multi-tenant)GitLab DedicatedGitLab Self-Managed
Who operates and maintainsGitLabGitLab (single tenant, hosted on AWS)Yourself (Omnibus, Helm, Operator)
VersionContinuous deployment, always up to dateGitLab management upgrade windowYou decide when to upgrade (released monthly, third Thursday)
PackageFree / Premium / UltimateUltimateCE (Free Open Source) or EE (Free/Premium/Ultimate License)
Administrator settingsNo instance administrator; group Owner is the highestPartially configurableFull control (Admin area, such as default branch protection, file size limit)
suitable formost teamsHigh data residency/isolation requirementsIntranet, offline, in-depth customization

The functions and packages used in this lesson (subject to the Tier annotation on the docs.gitlab.com page)

FunctionFreePremiumUltimate
Protected branches (allow merge/push by role, allow force push)✓✓✓
Protected branches are assigned to specific users/groups, group-level protected branches—✓✓
push mirror✓✓✓
Pull mirror—✓✓
MR requires approval and multiple approval rules—(Free only with optional approval)✓✓
CODEOWNERS and code owner approval—✓✓
Push rules (commit message rules, prohibited confidential files, file size)—✓✓
Confidential push protection (key detection by content), security approval——✓

When:How to choose

sceneRecommendedReason
All workloads are in AWS, identities are unified in IAM Identity Center, and the code is required not to leave the AWS account/regionCodeCommitNo additional identity system; VPC interface endpoints; CloudTrail auditing; KMS
Requires Issue, MR, CI, and product library integration, multi-cloudGitLabPlatform intact; CodeConnections can still connect it to AWS
The main repository is in GitLab/GitHub, but systems within AWS (such as build machines in isolated networks) need to read the codeMain repository + CodeCommit read-only mirrorM7 push image; or use CodeConnections to connect directly
Large collection of binary assets (games, ML models)GitLab / GitHub(LFS)CodeCommit does not support LFS as of verification date, single blob is limited to 2 GB
Common misunderstandings① "CodeCommit has been discontinued" - it will only stop new customers in 2024, existing customers will always be available, and will be fully restored from 2025-11. ② "GitLab Free can force MR approval" - Free approval is optional, required approval and CODEOWNERS approval require Premium. ③ "CodeConnections will copy the GitHub repository to AWS" - it only authorizes the AWS service to call the provider API/pull code, not a mirror.

Architecture diagram: Identity and repository models for both platforms

AWS account 111122223333 IAM Identity CenterUser → Permission Set→ AWSReservedSSO_* roles(temporary credentials) IAM policyAllow codecommit:GitPull/PushDeny GitPush whenReferences = refs/heads/main Region ca-central-1 · CodeCommit repo: myappKMS encryption · PR · Approval rules Notification rules/triggersSNS · Lambda · EventBridge GitLab(.com / Dedicated / Self-Managed) Top-level group acme (the package takes effect at this level)Member roles: Guest · Planner · Reporter · Developer · Maintainer · Owner subgroup platformrole inheritance Project myappRepository · MR · CI · Issue Project Settings → RepositoryProtected branches · Push rules · Mirrors · Deployment keysMerge Requests: Approval Rules · CODEOWNERS · Merge Methods
Figure 1-1 CodeCommit hands over “who can do what” to IAM; GitLab uses its own role system and inherits by group

Timeline: CodeCommit status changes

2015-07publish 2020-03git-remote-codecommit 2024-07-25Stop new customers 2025-11-24Restore GA (29 regions) 2026 Q1 PlanGit LFS (not yet online) Planned starting from Q3 2026eu-south-2 / ca-west-1
Figure 1-2 Green indicates what has happened, red indicates restrictions, and yellow indicates the roadmap (subject to the user guide document history)

Interaction: Timeline playback + platform selector

First play the CodeCommit timeline to see clearly "Can new customers create repositorys" at each stage; then check your team constraints, and the selector will give recommended combinations and reasons.

Click play.

platform selector

Check the left constraint...

Core command: Confirm platform status

commandfunctionDescription
aws codecommit list-repositoriesList repositorys in the current regionBeing able to return (even if it is an empty list) indicates that the account can use CodeCommit
aws codecommit create-repositoryCreate repositoryNew accounts were rejected between 2024-07 and 2025-11; should succeed now
aws ssm get-parameters-by-path --path /aws/service/global-infrastructure/services/codecommit/regionsQuery service available areasAWS public parameters, the results are subject to the actual return
glab api versionQuery GitLab instance versionSelf-Managed Check before and after upgrade
glab api namespaces/:id/Group settings pageView group packagesPackages are hung on top-level groups
aws codecommit list-repositories --profile cc-dev --region ca-central-1
aws ssm get-parameters-by-path \
  --path /aws/service/global-infrastructure/services/codecommit/regions \
  --query 'Parameters[].Value' --output text --profile cc-dev | tr '\t' '\n' | sort | wc -l
glab api version
{
    "repositories": []
}
29
{"version":"19.5.x-ee","revision":"…","kas":{…},"enterprise":true}

How to verify:The number of regions should be consistent with the AWS announcement of 29 (may change at different times).Common mistakes:Forgot--region, the CodeCommit repository is a regional resource, and you "cannot see the repository" if you change the region.Production use:Put these checks into the platform inspection script to detect service status or version changes in a timely manner.

Lab 1: Confirm that both platforms are available (~3 minutes)

CodeCommit: Create a temporary repository and delete it
aws codecommit create-repository --repository-name probe-$(date +%s) \
  --repository-description "M1 probe" --profile cc-dev --region ca-central-1 \
  --query 'repositoryMetadata.[repositoryName,cloneUrlHttp]' --output text
probe-1763190000	https://git-codecommit.ca-central-1.amazonaws.com/v1/repos/probe-1763190000
aws codecommit delete-repository --repository-name probe-1763190000 --profile cc-dev --region ca-central-1
GitLab: View your namespace and packages
glab api user | python3 -c 'import sys,json; u=json.load(sys.stdin); print(u["username"], u["id"])'
glab api "groups?min_access_level=50" | python3 -c 'import sys,json; [print(g["full_path"]) for g in json.load(sys.stdin)]'

If there is no group, create a new group on gitlab.com (for examplealice-git-lab), in which M5 subsequently creates projects. Plans are viewed in the group's "Settings → Usage Quota/Billing".

Document decisions: In the myapp repositorydocs/adr/0004-hosting.mdWrite down your platform choice and reasons (ADR, architectural decision record) and commit it to the local branchdocs/adr-hosting, M5 will merge it via MR.
cd ~/git-lab/myapp && git switch -c docs/adr-hosting
mkdir -p docs/adr && printf '# ADR 0004: Hosting\n\nPrimary: GitLab.com\nMirror: AWS CodeCommit (ca-central-1), read-only for humans\n' > docs/adr/0004-hosting.md
git add docs/adr/0004-hosting.md && git commit -m "docs: ADR 0004 hosting decision"

Case 1: If you move out in 2024, do you want to move back in 2026?

Question:A financial team moved 120 CodeCommit repositorys to GitLab Self-Managed in 2024. After AWS announced the restoration of GA in 2025-11, someone proposed to move them back.Method:Based on the four assessments of "identity unification, compliance, functional gaps, and operation and maintenance costs": GitLab has undertaken CI and security scanning, and the relocation needs to rebuild the pipeline; final decisionDo not move back, only build CodeCommit read-only images for build machines in an AWS isolated network.Limitations:Mirroring only synchronizes Git references, MR discussions and issues will not be synchronized.

Case 2: Compliance requires code not to leave the AWS account

Question:Supervised workloads require that the source code repository and CloudTrail auditing are in the same account and in the same region.Method:Choose CodeCommit + VPC interface endpoint (git-codecommit with codecommitTwo endpoint services) + customer-managed KMS keys that developers access through the Identity Center permission set.Limitations:No LFS; put large files in S3 and keep only the manifest in the repository.

Case 3: GitLab.com Free group suddenly cannot add members

Question:After converting from open source to private, the Free private namespace is affected by the upper limit on the number of members, and new members are placed in a waiting state.Method:Evaluate Premium or move public projects back to public; confirm caps are subject to GitLab.com's current policies.Inspiration:When selecting the platform, write the package restrictions into the ADR.

Common errors and solutions

An error occurred (OperationNotAllowedException) when calling the CreateRepository operation … (new accounts from 2024-07 to 2025-11)

Reason:CodeCommit is not accepting new customers during this period.Current status:It has been restored as of 2025-11-24 and new accounts should be able to be created. If the error still occurs, check whether SCP (Organizational Service Control Policy) is disabled.codecommit:*, and whether the selected region is in the support list. The exception name is subject to the actual return.

aws codecommit create-repository --repository-name t1 --region ca-central-1 --debug 2>&1 | grep -i -E "error|denied" | head
Could not connect to the endpoint URL: "https://codecommit.eu-south-2.amazonaws.com/"

Reason:CodeCommit is not yet available in this region (regions on the roadmap do not have endpoints until they go live).Fix:Use a supported region instead, or query SSM public parameters to confirm.

GitLab: This feature is only available on Premium and Ultimate / "Push rules" or "Approval rules" cannot be seen on the settings page

Reason:The feature is not in the current package, or the top-level group in which the item is located is Free.Fix:Confirm which top-level group the project belongs to and its package; projects under the personal namespace inherit the package of the personal namespace.

Command line operation questions
1. List the names of all CodeCommit repositories in ca-central-1 with one command.
aws codecommit list-repositories --region ca-central-1 --query 'repositories[].repositoryName' --output text
2. Query the version number of the current GitLab instance.
glab api version | python3 -c 'import sys,json; print(json.load(sys.stdin)["version"])'
Scenario analysis questions
80% of the team's workload is on AWS, but the game art assets are numerous and require issue tracking. What combination would you recommend?

The main repository is placed in GitLab (or GitHub) that supports LFS and Issues, and CodeConnections is used to connect the repository to CodePipeline; if an AWS internal read-only copy is required, a CodeCommit push image can be made to the repository without LFS. CodeCommit still does not support LFS as of the verification date. The upper limit of a single blob is 2 GB, which is not suitable as the main repository for art assets.

Verified instructional videos

▶
Git for GitLab (Beginner's FULL COURSE) — Valentin Despa
English · Using GitLab as a platform to explain the basics of Git and the MR process (recorded earlier than GitLab 19, the interface is subject to the current version)

No verified AWS CodeCommit special video was found (especially after GA is restored in 2025-11), please refer to the official documents and the storyboard below.

Official documentation

Video storyboard (approximately 60 seconds)

Shot 1 · 0–15s
Screen: Timeline, red "Stop New Customers" appears at 2024-07.
Narrator: In July 2024, CodeCommit stopped accepting new customers, and many teams began to move out.
Shot 2 · 15–30s
Screen: 2025-11-24 turns green, showing "29 regions, unchanged price, SLA 99.9%".
Narrator: In November 2025, AWS announced that CodeCommit would be fully available again, and the roadmap included Git LFS and new regions.
Shot 3 · 30–60s
Screen: AWS account + IAM on the left, GitLab group + role on the right, and a mirror arrow in the middle.
Narrator: CodeCommit uses IAM to manage permissions, and GitLab uses role and group inheritance. Many teams combine the two: GitLab serves as the main repository, and CodeCommit serves as the read-only mirror.
or score ≥ 70% on the Quiz

Module 2 · CodeCommit: Authentication and git-remote-codecommit

05:00 – 13:00 · CodeCommit does not have an “account password”, only an IAM identity; the four connection methods essentially translate the IAM identity into credentials that can be used by Git
8 minutesGRC = Federated/Temporary Credentials Recommended MethodGit Credentials = IAM User Easiest★★★★★
learning objectives
  • Select the connection method according to AWS official recommendations: federated identity, IAM Identity Center, temporary credentials, root account →git-remote-codecommit;IAM User →HTTPS Git credentials(easiest) or git-remote-codecommit; SSH and AWS CLI Credential Assistant are alternatives.
  • Explain how git-remote-codecommit works: remote helper → botocore reads credentials →SigV4 signatureGenerate one-time password → HTTPS transport over Git.
  • Skilled use aws codecommitManage repositories, branches, and PRs.
Prerequisite knowledge:Credential Assistant for Lesson 3; AWS CLI Profiles.Importance:★★★★★ (80% of CodeCommit issues are authentication issues)

What: Four connection methods

wayClone URLIdentity typeCredential formAWS Documentation Location
git-remote-codecommit(GRC)codecommit::ca-central-1://cc-dev@myappIAM Identity Center, federated identities, roles, root accounts, IAM usersUse AWS credentials for each connectionCurrent calculation SigV4 signatureFederated/Temporary Credentials AccessRecommendedway; also available for IAM users without generating Git credentials
HTTPS + Git credentialshttps://git-codecommit.ca-central-1.amazonaws.com/v1/repos/myappIAM users onlyIAM generatedstaticUsername/password (max 2 sets per user)"The easiest way to set up CodeCommit", compatible with IDEs and third-party tools
SSHssh://git-codecommit.ca-central-1.amazonaws.com/v1/repos/myappIAM users onlyUpload the public key to the IAM user with the SSH username SSH key ID (APKA…)Alternative; requires manual management of key files
HTTPS + AWS CLI Credential AssistantSame as HTTPSIAM users, EC2 instance roles, etc.aws codecommit credential-helpercash signatureAlternative; prone to conflict with System Credential Assistant (M7)
Recommended order (in conjunction with IAM best practices)The best practice for IAM is "for human users to federate access through an identity provider, using temporary credentials." So in a team environment:① git-remote-codecommit + IAM Identity Center configuration file(preferred, no long-term keys) →② HTTPS Git credentials(Only applicable to scenarios where users are still using IAM, such as the M7 mirror robot in this lesson, or it does not supportcodecommit://URL's IDE) → ③ SSH (IAM users, environments that prefer SSH) → ④ CLI Credential Assistant (old script for EC2 instance roles). The original AWS text is: "Git credentials are the easiest way" "For federated access, temporary credentials, or web identity providers where Git credentials cannot be used, git-remote-codecommit is recommended."

Why: Why HTTPS Git credentials don't work for SSO users

Git credentials (service-specific credential) are IAMUsersubresource ofiam:CreateServiceSpecificCredentialgenerated; the Identity Center user is just aAssumed role session, no IAM user object can hang credentials. So SSO users can only use GRC or CLI Credential Helpers - both of which are signed with temporary credentials for the current session.

How: Internal process of git-remote-codecommit

  1. remote helper dispatch: Git sees URL schemecodecommit(formed likecodecommit::REGION://PROFILE@REPOorcodecommit://PROFILE@REPO), executed in PATHgit-remote-codecommit <remote> <url>(withgit-remote-httpssame mechanism).
  2. Parse URL: Get the area (the default is to get the area of the configuration file), the configuration file name (the defaultdefault), repository name.
  3. Get credentials: Resolve credential chain by profile via botocore - SSO cache (~/.aws/sso/cache)、role_arnSubstitute, environment variables, etc., and getAccessKeyId / SecretAccessKey / SessionToken。
  4. SigV4 signature:Request for specification (methodGIT, path/v1/repos/myapp, host header) with service namecodecommit, region, current UTC time to derive the signing key and compute the HMAC-SHA256 signature.
  5. Construct credentials:username = access key ID (appended if there is a session token%+ session token), password =Timestamp Z + Signature; spelled intohttps://username:password@git-codecommit.REGION.amazonaws.com/v1/repos/myapp。
  6. Leave it to Git HTTPS transport: callgit remote-https, follow-upinfo/refs、git-upload-pack/git-receive-packAll use normal Smart HTTP. The server uses the same algorithm to verify the signature, check the time offset, and then use IAM to evaluatecodecommit:GitPull/GitPushPermissions (M3’s conditional policy takes effect here).

The above steps 4–5 are organized based on the git-remote-codecommit open source implementation (github.com/aws/git-remote-codecommit). They are implementation details and may be adjusted by AWS. For users, just remember:The password is a short-term valid signature and will not be lost. Once the credentials expire, it will be reset.aws sso login。

When: Typical scenarios for each method

sceneChoose
Developer Notebook, Corporate Identity CenterGRC + SSO configuration file
Cross-account access (the repository is in a shared service account)GRC + configuration filerole_arn/source_profile
GitLab pushes images and third-party SaaS. You can only fill in the username and password.Dedicated IAM user + HTTPS Git credentials (least privilege)
CodeBuild/EC2/Lambda internalsUsing service roles: CodeBuild native integration; GRC (Default Credential Chain) or CLI Credential Assistant available on EC2
IDE does not recognizecodecommit://Clone with GRC on the command line and open with IDE, or use Git credentials

Compare to Lesson 3

CodeCommitGitHubAzure ReposGitLab
Recommended Human AuthenticationGRC + Identity CenterGCM (OAuth Browser Flow)GCM + Entra IDGCM/glab (OAuth) or PAT
static credentialsGit credentials (IAM user)Fine-grained PATPATPAT/Project Access Token/Deployment Token
SSHRSA public key linked to IAM userAccount SSH key/deployment keySSH public keyUser SSH Key/Deployment Key
Common misunderstandings① "GRC will send my access key to the server" - No, only the access key ID and signature are sent, and the private access key is only used for local calculation of HMAC. ② "Git credentials are IAM access keys" - No, it is a service-specific credential specially used for CodeCommit, which can be revoked independently after being leaked. ③ "SSH username fill in git" - CodeCommit's SSH username is the one displayed in IAMSSH key ID(BEGIN APKA).

Sequence diagram: git push to CodeCommit via git-remote-codecommit

git push git-remote-codecommit botocore / ~/.aws CodeCommit frontend IAM authorization ① exec helper(codecommit:: URL) ② Parse the credentials of profile cc-dev AKID/Secret/SessionToken (SSO cache) ③ SigV4:GIT /v1/repos/myappHMAC-SHA256 (local) ④ HTTPS Basic: AKID%Token: 20261115T101500Z+ signature ⑤ Signature verification + evaluation GitPush Allow / Deny (including References condition) ⑥ receive-pack result: ok refs/heads/feature or 403 Private access keys never leave the machine; signatures are timestamped and valid for a few minutes
Figure 2-1 GRC “translates” IAM temporary credentials into one-time HTTPS passwords

Decision chart: Which approach should I use?

Are you identified as an IAM user?get-caller-identity see ARN No (assumed-role/SSO) git-remote-codecommit(or CLI Credential Assistant) Yes Does the tool only support username/password?IDE, GitLab image, third-party SaaS Yes HTTPS Git credentials No GRC (no Git credentials required)or SSH (when SSH is preferred)
Figure 2-2 Look at identity types first, then tool limitations

Core Animation: git-remote-codecommit uses IAM temporary credentials for SigV4 signing

Observe step by stepgit push cc feature/loginWhat happens behind the scenes. You can switch between "Credential Status" and "IAM Policy" to see the failure path. Signature values are indicative.

Ready.
$ git push cc feature/login

Core commands and parameters

commandfunctionKey parameters/description
git clone codecommit::REGION://PROFILE@REPOGRC cloneOmit the region to use the configuration file region; omitPROFILE@Use default
git remote add cc codecommit::ca-central-1://cc-dev@myappAdd CodeCommit remote to existing repositoryRemote name is arbitrary
aws iam create-service-specific-credentialGenerate Git credentials for IAM user--service-name codecommit.amazonaws.com;The password is only displayed once
aws iam upload-ssh-public-keyUpload SSH public keyReturnSSHPublicKeyId(APKA…) as SSH username
aws codecommit create-repositoryCreate repository--repository-name --repository-description --kms-key-id --tags
aws codecommit get-repositoryView clone URL, default branchcloneUrlHttp、cloneUrlSsh、defaultBranch
aws codecommit list-branches / get-branchView branches--repository-name --branch-name
aws codecommit update-default-branchModify default branch--default-branch-name main
aws codecommit create-pull-requestCreate a PR--targets repositoryName=,sourceReference=,destinationReference=
aws codecommit list-pull-requestsList PRs--pull-request-status OPEN

Method ①: GRC + IAM Identity Center (recommended)

aws sso login --profile cc-dev
cd ~/git-lab/myapp
aws codecommit create-repository --repository-name myapp --repository-description "Git course lab" \
  --profile cc-dev --region ca-central-1 --query repositoryMetadata.arn --output text
git remote add cc codecommit::ca-central-1://cc-dev@myapp
git push cc main
git push cc --tags
arn:aws:codecommit:ca-central-1:111122223333:myapp
Enumerating objects: 58, done.
…
To codecommit::ca-central-1://cc-dev@myapp
 * [new branch]      main -> main
 * [new tag]         v1.0.0 -> v1.0.0

Cross-account: Assume the role in the configuration file

[profile cc-shared]
source_profile = cc-dev
role_arn       = arn:aws:iam::444455556666:role/CodeCommitCrossAccount
region         = ca-central-1
git clone codecommit://cc-shared@platform-libs

Method ②: IAM user + HTTPS Git credentials

aws iam create-service-specific-credential --user-name gitlab-mirror-bot \
  --service-name codecommit.amazonaws.com \
  --query 'ServiceSpecificCredential.[ServiceUserName,ServicePassword,ServiceSpecificCredentialId]' --output text
gitlab-mirror-bot-at-111122223333	AbCdEf…=	ACCAXXXXXXXXXXXXXXXXX

Username looks likeUsername-at-account ID. Git will pop up a username/password prompt when cloning, or it will be saved by the system credential assistant (GCM, osxkeychain).Note:Do not configure the AWS CLI Credential Assistant at the same time, otherwise a conflict will occur (M7).

Method ③: SSH

ssh-keygen -t rsa -b 4096 -f ~/.ssh/codecommit_rsa -N ''
aws iam upload-ssh-public-key --user-name alice-iam \
  --ssh-public-key-body file://~/.ssh/codecommit_rsa.pub --query SSHPublicKey.SSHPublicKeyId --output text
cat >> ~/.ssh/config <<'EOF'
Host git-codecommit.*.amazonaws.com
  User APKAEIBAERJR2EXAMPLE
  IdentityFile ~/.ssh/codecommit_rsa
EOF
ssh git-codecommit.ca-central-1.amazonaws.com
You have successfully authenticated over SSH. You can use Git to interact with AWS CodeCommit. Interactive shells are not supported.Connection to git-codecommit.ca-central-1.amazonaws.com closed by remote host.

SSH public key requirements for IAMssh-rsa(OpenSSH) or PEM format, at least 2048 bits; other types such as ed25519 are subject to the IAM documentation. This lesson uses RSA.

Method ④: AWS CLI Credential Assistant (just understand it)

# Only takes effect on the CodeCommit host to avoid affecting GitHub/GitLab
git config --global credential.https://git-codecommit.ca-central-1.amazonaws.com.helper ''
git config --global --add credential.https://git-codecommit.ca-central-1.amazonaws.com.helper '!aws codecommit credential-helper $@'
git config --global credential.https://git-codecommit.ca-central-1.amazonaws.com.UseHttpPath true

The first line sets a null value to clear the helper list inherited from the global (for examplemanager、osxkeychain), which is the key to avoiding "403 after one hour" in M7.

Experiment 2: Access the same repository in three ways (about 7 minutes)

GRC pushes all branches and tags of myapp(Continued from the paging method of the above command ①)
cd ~/git-lab/myapp
git push cc --all && git push cc --tags
aws codecommit list-branches --repository-name myapp --profile cc-dev --region ca-central-1
{
    "branches": ["main", "feature/login", "docs/adr-hosting", "release/1.0"]
}
Verify that the signature is "temporary": Exit the SSO session before pulling.
aws sso logout
git fetch cc
aws sso login --profile cc-dev && git fetch cc && echo "fetch ok"
… Error when retrieving token from sso: Token has expired and refresh failed
fatal: … (git-remote-codecommit exits)
fetch ok

The error text varies with botocore version; the key isGRC fails directly when there are no credentials available locally., you will not be prompted for a password.

(Optional) Create a mirrorbot IAM user and Git credentials:M7 To use it to push the image, build it first and grant only the minimum permissions to the repository.
ACCOUNT=$(aws sts get-caller-identity --profile cc-dev --query Account --output text)
aws iam create-user --user-name gitlab-mirror-bot --profile cc-admin
cat > mirror-policy.json <<EOF
{ "Version": "2012-10-17",
  "Statement": [{ "Effect": "Allow",
    "Action": ["codecommit:GitPull","codecommit:GitPush"],
    "Resource": "arn:aws:codecommit:ca-central-1:${ACCOUNT}:myapp-mirror" }] }
EOF
aws iam put-user-policy --user-name gitlab-mirror-bot --policy-name MirrorPushOnly \
  --policy-document file://mirror-policy.json --profile cc-admin

cc-adminIs a profile with IAM administrative permissions (Identity Center Admin permission set). repositorymyapp-mirrorWill be created in M7; ARN must explicitly include region and account (GitLab documentation also emphasizes this).

Create a PR using the CLI:
aws codecommit create-pull-request --title "docs: hosting ADR" \
  --targets repositoryName=myapp,sourceReference=docs/adr-hosting,destinationReference=main \
  --profile cc-dev --region ca-central-1 --query 'pullRequest.[pullRequestId,pullRequestStatus]' --output text
1	OPEN
Cleanup (this module):PR is reserved for M3; do not delete the myapp repository. If you have created an SSH public key, useaws iam delete-ssh-public-key --user-name … --ssh-public-key-id APKA…Delete.

Case 1: Retiring IAM users and long-term Git credentials

Question:A security audit found that 200 IAM users each had Git credentials, and that the departing employee's credentials were still valid.Method:Full switch to Identity Center + GRC: Publishing standards~/.aws/configtemplate andgit remote set-url origin codecommit::ca-central-1://dev@REPOScript; IAM users are reserved only for mirror bots and discover idle credentials with IAM Access Analyzer's "Unused Access".Limitations:Some IDE plug-ins are not recognizedcodecommit://, training "Clone with command line first and then open with IDE".

Case 2: CI build machine accesses CodeCommit on private subnet

Question:The EC2 build machine does not have a public network outlet.git clonetimeout.Method:Create an interface VPC endpointcom.amazonaws.ca-central-1.git-codecommit(Git traffic) andcom.amazonaws.ca-central-1.codecommit(API), enable private DNS; build machine instance role + GRC.Limitations:Terminal nodes are billed by hour and traffic; terminal node policies can also limit accessible repositorys.

Case 3: Cross-account shared library repository

Question:Multiple business accounts need to read the shared service accountplatform-libs。Method:Create a read-only role in the shared account (trust the business account), and write the configuration file of the business developerrole_arn + source_profile, GRC is automatically substituted.Benefits:There are no long-term keys across accounts.

Common errors and solutions

git: 'remote-codecommit' is not a git command. See 'git --help'.

Reason:git-remote-codecommitNot in PATH (pipx/--user installation directory is not added to PATH).

command -v git-remote-codecommit || ls ~/.local/bin/
pipx ensurepath && exec $SHELL -l
error: externally-managed-environment(pip install git-remote-codecommit)

Reason:Python on systems such as Ubuntu 24.04 / Debian 12 follows PEP 668.Fix:use pipx install git-remote-codecommitor virtual environment; do not use--break-system-packages. AWS troubleshooting documentation also supplements this situation.

fatal: unable to access 'https://git-codecommit.ca-central-1.amazonaws.com/v1/repos/myapp/': The requested URL returned error: 403

Reasons (by probability):① Credential Assistant conflict, keychain caches expired signing password; ② IAM NoneGitPull/GitPushOr it is rejected by the conditional policy; ③ The region is written incorrectly (the repository is in another region); ④ The Git credentials are deactivated.

git config --show-origin --get-all credential.helper
GIT_TRACE=1 GIT_CURL_VERBOSE=1 git ls-remote cc 2>&1 | grep -E "helper|HTTP/|403" | head
aws codecommit get-repository --repository-name myapp --region ca-central-1

Fix:See the M7 troubleshooting tree; troubleshoot Credential Assistant first, then check IAM.

Permission denied (publickey).(SSH)

Reason:~/.ssh/configThe User is not an SSH key ID, the public key status is Inactive, or a key type not accepted by IAM is used.

ssh -v git-codecommit.ca-central-1.amazonaws.com 2>&1 | grep -E "Offering|Authenticated|denied"
aws iam list-ssh-public-keys --user-name alice-iam
Unable to locate credentials / The SSO session associated with this profile has expired

Fix:aws sso login --profile cc-dev;Confirm that the configuration file name in the URL matches~/.aws/configConsistent (case sensitive).

Command line operation questions
1. Change the existing remote origin from HTTPS Git credential mode to GRC mode (configuration file dev, region ca-central-1, repository api).
git remote set-url origin codecommit::ca-central-1://dev@api
git remote -v
2. List all CodeCommit Git credentials for the IAM user gitlab-mirror-bot and deactivate one of them.
aws iam list-service-specific-credentials --user-name gitlab-mirror-bot --service-name codecommit.amazonaws.com
aws iam update-service-specific-credential --user-name gitlab-mirror-bot --service-specific-credential-id ACCAXXXX --status Inactive
Scenario analysis questions
When a new employee logs in to the console through Identity Center, he cannot find the entry "Generate HTTPS Git Credentials for CodeCommit" in IAM and asks if the permissions are insufficient. How do you explain and guide?

Identity Center users are role sessions in IAM and do not have IAM user objects, so Git credentials cannot be generated - not a permissions issue. Instruct him to install AWS CLI v2 and git-remote-codecommit, executeaws configure sso with aws sso login, copied using the console "Clone URL → HTTPS (GRC)"codecommit::area://config file@repositoryAddress cloning.

Instructional video

No verified git-remote-codecommit feature video found. Here are oEmbed-verified general Git videos to review HTTPS/SSH remote basics:

▶
Git Tutorial for Beginners: Learn Git in 1 Hour — Programming with Mosh
English · Git basics and remote repository

Official documentation

Video storyboard (approximately 90 seconds)

Shot 1 · 0–20s
Screen: terminal inputgit push cc main, URLs starting with codecommit:: are highlighted.
Narrator: Git saw the codecommit solution and went to find a helper program called git-remote-codecommit.
Shot 2 · 20–45s
Screen: The key icon flies out from ~/.aws/sso/cache and becomes three segments: access key ID, private key, and session token.
Narrator: The helper program reads the temporary credentials for the SSO session. The private key only participates in the calculation locally.
Shot 3 · 45–70s
Screen: HMAC operation animation, outputting "timestamp Z plus signature" as password.
Narrator: It uses SigV4 to calculate a one-time password and delivers it to Git's HTTPS transport.
Shot 4 · 70–90s
Screen: Server signature verification, IAM balance determines Allow or Deny.
Narrator: After the server verifies the signature, IAM determines whether it can be pushed. When the session expires, just log in again. There is no long-term password to keep.
or score ≥ 70% on the Quiz

Module 3 · CodeCommit: Branch protection, approval rules and notifications

13:00 – 21:00 · CodeCommit does not have a “branch protection” switch: protecting main relies on IAM denial policies, and forcing review relies on approval rules. Both are indispensable.
8 minutescodecommit:References + NullApproval rules don't block git push★★★★★
learning objectives
  • Write the officially recommended IAM policy for "restricting pushes and merging to branches":Denypush/merge/delete/file API, conditionsStringEqualsIfExists codecommit:References + Null codecommit:References = false, and explainNullWhy is it necessary.
  • Create an approval rule template (DestinationReferences、NumberOfApprovalsNeeded、ApprovalPoolMembers), associated to the repository, understanding that it only constrains PR merges.
  • Distinguish between notification rules (CodeStar Notifications → SNS/Chatbot), repository triggers (SNS/Lambda, up to 10) and EventBridge events.
Prerequisite knowledge:IAM policy evaluation (explicit Deny takes precedence).Importance:★★★★★

What: CodeCommit’s three-layered “guardrails”

layermechanismWhat can be preventedCan't stop anything
① IAM condition policyDeny + codecommit:Referencesdirectgit pushGo to main and console to change files, merge PRs, and delete branches.An identity that has full permissions for the repository and is not subject to this policy (for example, administrator)
② Approval rules (template)Rules are automatically generated on the PR and cannot be merged until they are met.Unapproved PR merge (console and Merge API)Direct git push(No PR); rules can be "overridden" by people with authority
③ Notification/Trigger/EventBridgeevent drivenDoes not prevent anything, only alerts, audits, and automates—

So what the GitHub rule set in Lesson 3 can do with “one click” is required on CodeCommit① + ②Combination: IAM refuses developers to push main directly, and PR’s merge permissions are controlled by approval rules; merge permissions are reserved for a few release managers or pipeline roles.

Why: Why is it neededNull Conditions

Official examples use bothStringEqualsIfExists and "Null": {"codecommit:References": "false"}, and explain: anyEffect is Deny and the action contains GitPushAll strategies must be addedNull, which is similar to Git andgit-receive-packrelated to the push method. It can be understood like this: oncegit pushDuring the authorization check, some requestsNot carriedReferences context (such as the negotiation phase), some carry updated ref lists:

  • Only useStringEqualsIfExists: The condition is "true" when the key does not exist → Deny takes effect →Pushing any branch is rejected。
  • plusNull = false(Require key exists): Requests where key does not exist do not match Deny; key exists and equalsrefs/heads/mainOnly reject → only protect main.

How: Complete list of actions for the strategy (official example)

GitPush、DeleteBranch、DeleteFile、PutFile、MergeBranchesByFastForward、MergeBranchesBySquash、MergeBranchesByThreeWay、MergePullRequestByFastForward、MergePullRequestBySquash、MergePullRequestByThreeWay. Just refuseGitPushis a common vulnerability - developers can still edit files on main directly in the console (PutFile) or merge the PR yourself.

The strategy should be linked toGroup or role(Official recommendation, do not hang up one user at a time); putResourceChange to*It can take effect on the main of all repositories in the account.

Approval rule template

  • Content JSON:Version "2018-11-08"、DestinationReferences(Target branch filtering, up to 100, wildcards available but not*beginning),Statements[].Type "Approvers"、NumberOfApprovalsNeeded、ApprovalPoolMembers(Approver pool, maximum 50).
  • How to write the approver pool:CodeCommitApprovers:account:nameMatches IAM users with the same name against federated users;assume role sessionneed to writearn:aws:sts::account:assumed-role/role name/*(Each session name counts as one approver). This is the case for Identity Center users.
  • Templates are managed by region (up to 1000 per region), requiredassociationto the repository; after associationNewRules will be generated only for PRs. Up to 30 rules on the PR (up to 25 of them from templates).
  • Cross-account approval is not supported; whether the PR author's approval counts depends on whether he is in the pool - excluding the author from the pool in production requires a process or an accurate listing of role sessions in the pool.
  • has permission (OverrideApprovalRules) can override the rule, and the override will generate an eventcodecommit-repository-approvals-rule-override, a warning should be issued.

Notifications, triggers, EventBridge

notification rulesrepository triggerEventBridge
APIAWS CodeStar Notifications(codestar-notifications)codecommit put-repository-triggersDefault event busaws.codecommit
eventComments, approval status/overrides, PR creation/update/status/merge, branch and tag creation/deletion/updateall、updateReference、createReference、deleteReferenceRepository status changes, PR status changes, comments, etc.
targetSNS (Standard), Chatbot (Slack/Teams); ≤ 10 goals per rule, ≤ 10 rules per resourceSNS standard topic (FIFO not supported), Lambda; ≤ 10 per repositoryAny EventBridge target
Purposemessage for peopleSimple automation (pushing to call Lambda)Complex routing, cross-account, startup pipeline

Compare with GitHub / Azure Repos / GitLab

AbilityCodeCommitGitHubAzure ReposGitLab
It is forbidden to push main directlyIAM Deny + ReferencesRule set “Require a pull request”Branch policy (enable to disable direct push)Protected branch Allowed to push = No one
Number of people required for approvalApproval rule templateNumber of rule set approvalsMinimum reviewer policyApproval Rules (Premium)
owner by pathNone (can only be based on the approver pool)CODEOWNERSAutomatically include reviewers (path filtering)CODEOWNERS(Premium)
Build verificationRequires EventBridge + CodeBuild to write back PR approval/comment by yourselfRequired status checkBuild a validation strategy"The assembly line must succeed"
Common misunderstandings① "After creating the approval rule template, main is safe" - directlygit push origin mainTo completely bypass the PR, must cooperate with IAM Deny. ② "Deny just writes GitPush" - console PutFile and Merge* API can still modify main. ③ "Old PRs will also take effect after template association" - rules will be automatically generated only for PRs created after association.

Flowchart: Who checks each push/merge?

git push cc mainDeveloper role IAM evaluation codecommit:GitPushReferences exists and = refs/heads/main→ Explicit Deny hit 403 Rejected (approval rules are not involved at all)Pushing to feature/* is not affected Merge PR #1 → mainConsole or merge-pull-request-* Are the approval rules met?2-approver-rule-for-mainApproved 1 / Required 2 IAM evaluation MergePullRequestBy*Is the merger Deny?(The role of the release leader is not Deny) both pass→ main move forward Ref updates when merging are performed by the CodeCommit service, which checks for Merge* actions, not GitPush
Figure 3-1 IAM governs "who can change main", and approval rules govern "whether the PR is qualified for merging"

Structure diagram: Approval rule template JSON

approval-rule-template-content Version: "2018-11-08"DestinationReferences: [refs/heads/main]Statements:Type: Approvers · NumberOfApprovalsNeeded: 2ApprovalPoolMembers: [ … ] Associated repository: myapp, api…associate-…-with-repository New PR target=main→ Automatically generate approval rules How to write the approver pool membersCodeCommitApprovers:111122223333:Maryarn:aws:sts::111122223333:assumed-role/AWSReservedSSO_Rev*/*(Each session counts 1 person)
Figure 3-2 Template → Association → New PR automatically brings rules

Interactive: IAM Conditional Policy Evaluator

Select "Request Type" and "Whether to carry References" to switch whether the policy includesNullCondition, observe whether explicit Deny hits. This is exactly the official requirement to addNullreason.




After selecting the parameters, click "Evaluate".

Core commands and parameters

commandfunctionDescription
aws iam create-policy / attach-role-policy / attach-group-policyCreate and mount a branch protection policyIn Identity Center, the policy is an inline/customer-managed policy for a permission set.
aws codecommit create-approval-rule-templateCreate template--approval-rule-template-contentJSON string
aws codecommit associate-approval-rule-template-with-repositoryassociated to repositoryFor batch usebatch-associate-…
aws codecommit get-pull-request-approval-statesView approval statusneed --revision-id
aws codecommit update-pull-request-approval-stateApprove/Withdraw Approval--approval-state APPROVE|REVOKE
aws codecommit evaluate-pull-request-approval-rulesDetermine whether the rules are metReturnapproved、overridden
aws codecommit override-pull-request-approval-rulesOverride rules (should be restricted and alert)--override-status OVERRIDE
aws codecommit merge-pull-request-by-squashMerge PRThere is also fast-forward / three-way
aws codecommit put-repository-triggers / test-repository-triggerstriggerevents:all / updateReference / createReference / deleteReference
aws codestar-notifications create-notification-rulenotification rules--event-type-idsSuch ascodecommit-repository-pull-request-created

1. Branch protection strategy (official example, changed to ca-central-1/myapp)

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Deny",
      "Action": [
        "codecommit:GitPush",
        "codecommit:DeleteBranch",
        "codecommit:DeleteFile",
        "codecommit:PutFile",
        "codecommit:MergeBranchesByFastForward",
        "codecommit:MergeBranchesBySquash",
        "codecommit:MergeBranchesByThreeWay",
        "codecommit:MergePullRequestByFastForward",
        "codecommit:MergePullRequestBySquash",
        "codecommit:MergePullRequestByThreeWay"
      ],
      "Resource": "arn:aws:codecommit:ca-central-1:111122223333:myapp",
      "Condition": {
        "StringEqualsIfExists": { "codecommit:References": ["refs/heads/main"] },
        "Null": { "codecommit:References": "false" }
      }
    }
  ]
}
aws iam create-policy --policy-name DenyChangesToMain --policy-document file://deny-main.json --profile cc-admin
# Method A: Hang to IAM group/role
aws iam attach-role-policy --role-name CodeCommitDevelopers \
  --policy-arn arn:aws:iam::111122223333:policy/DenyChangesToMain --profile cc-admin
# Method B: Identity Center permission set attached to customer managed policy
aws sso-admin attach-customer-managed-policy-reference-to-permission-set \
  --instance-arn arn:aws:sso:::instance/ssoins-xxxx --permission-set-arn arn:aws:sso:::permissionSet/ssoins-xxxx/ps-xxxx \
  --customer-managed-policy-reference Name=DenyChangesToMain --profile cc-admin
aws sso-admin provision-permission-set --instance-arn … --permission-set-arn … --target-type ALL_PROVISIONED_ACCOUNTS

2. Approval rule template (requires 2 review role sessions for approval)

aws codecommit create-approval-rule-template \
  --approval-rule-template-name 2-approver-rule-for-main \
  --approval-rule-template-description "Requires two reviewers if the destination branch is 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_CodeCommitReviewer_*/*"]}]}' \
  --profile cc-admin --region ca-central-1
aws codecommit associate-approval-rule-template-with-repository \
  --approval-rule-template-name 2-approver-rule-for-main --repository-name myapp --profile cc-admin --region ca-central-1

The role name generated by Identity Center has a random suffix (AWSReservedSSO_permission set name_xxxxxxxx), so pool members use wildcards. The official example writing method isarn:aws:sts::123456789012:assumed-role/CodeCommitReview/*。

3. Approval and Merger

PR=1
REV=$(aws codecommit get-pull-request --pull-request-id $PR --query pullRequest.revisionId --output text)
aws codecommit update-pull-request-approval-state --pull-request-id $PR --revision-id $REV --approval-state APPROVE --profile reviewer1
aws codecommit evaluate-pull-request-approval-rules --pull-request-id $PR --revision-id $REV
aws codecommit merge-pull-request-by-squash --pull-request-id $PR --repository-name myapp --profile release
{
    "evaluation": {
        "approved": false,
        "overridden": false,
        "approvalRulesSatisfied": [],
        "approvalRulesNotSatisfied": ["2-approver-rule-for-main"]
    }
}

4. Notification rules and triggers

TOPIC=$(aws sns create-topic --name myapp-repo-events --query TopicArn --output text)
aws codestar-notifications create-notification-rule --name myapp-pr-events \
  --resource arn:aws:codecommit:ca-central-1:111122223333:myapp --detail-type FULL \
  --event-type-ids codecommit-repository-pull-request-created codecommit-repository-pull-request-merged codecommit-repository-approvals-rule-override \
  --targets TargetType=SNS,TargetAddress=$TOPIC
cat > trigger.json <<EOF
{ "repositoryName": "myapp",
  "triggers": [{ "name": "main-updated", "destinationArn": "$TOPIC", "customData": "git-course",
                 "branches": ["main"], "events": ["updateReference"] }] }
EOF
aws codecommit test-repository-triggers --cli-input-json file://trigger.json
aws codecommit put-repository-triggers --cli-input-json file://trigger.json

When you create a notification rule through the console, the access policy will be automatically configured for the newly created SNS topic; when using an existing topic using the CLI, you need to allow it in the topic policy.codestar-notifications.amazonaws.comPublish (see official "Configure Amazon SNS topics for notifications").

Lab 3: Protect myapp’s main and ask for approval (~7 minutes)

Mount DenyChangesToMainArrive cc-devPermission set/role used (see Commands tab), wait approximately 1 minute for IAM changes to propagate.
Verify that the direct push to main is rejected, and the feature is not affected.
cd ~/git-lab/myapp && git switch main
git commit --allow-empty -m "test: direct push to main"
git push cc main
git switch -c feature/m3-test && git commit --allow-empty -m "test: feature push" && git push cc feature/m3-test
fatal: unable to access 'https://git-codecommit.ca-central-1.amazonaws.com/v1/repos/myapp/': The requested URL returned error: 403
…
 * [new branch]      feature/m3-test -> feature/m3-test

CodeCommit returns HTTP 403 for IAM rejection and does not give a text description of "protected branch" like GitLab does - this is where it is most likely to be misjudged as "credential error" during debugging (M7). Undo local test commit:git switch main && git reset --hard cc/main。

Verification console cannot change main: Open myapp → main → README → Edit → Commit in the CodeCommit console, and you should see a permission error; switch to the feature branch and it will be successful.
Create and associate approval rule templates(Command Pagination Step 2; without a review permission set you can change the pool members to your own session ARN and set the quantity to 1).
Create a new PR and observe the rules
aws codecommit create-pull-request --title "test: m3" \
  --targets repositoryName=myapp,sourceReference=feature/m3-test,destinationReference=main \
  --query 'pullRequest.approvalRules[].approvalRuleName' --output text
2-approver-rule-for-main

PR #1 created by M2 was created before the associated template,NoAutomatically bring rules - you can compare the two.

(optional) notification: Create an SNS topic and subscribe with email, create notification rules, comment on PR, and check emails.
Cleanup (this module): Keep strategies and templates for comprehensive experiments; delete test branches:git push cc --delete feature/m3-test(If it is rejected, it means you wrote Resource for all branches).

Case 1: Only GitPush is rejected, the console is used to "hotfix" main

Question:The audit found that there was a commit without PR on main, and the author directly edited the configuration file in the console.Root cause:Deny strategy only writescodecommit:GitPush。Fix:Replace with the official complete action list (includingPutFile、DeleteFile, allMerge*) and query with CloudTrailPutFileEvents are traced back.

Case 2: The approver pool is written as the IAM user name, and no one can approve it after SSO.

Question:After migrating to Identity Center, all PRs are stuck at "0/2 Approved".Root cause:The pool members areCodeCommitApprovers:…:Mary, only matches IAM users and federated users, not assumed role sessions.Fix:Change toarn:aws:sts::account:assumed-role/AWSReservedSSO_Reviewer_*/*, after updating the template, you need to manually update the rules or re-create the existing PR.

Case 3: Use EventBridge to push "Approval rules overridden" to the secure channel

Method:Notification rule subscriptioncodecommit-repository-approvals-rule-override, targeting Chatbot (Slack); also restricted with SCPcodecommit:OverrideApprovalRulesOnly break-glass roles are allowed.Effect:Releases are still available in emergencies, but every coverage leaves a mark and is reviewed instantly.

Common errors and solutions

The requested URL returned error: 403 (push to any branch is rejected)

Reason:Deny strategy is missingNullConditions, or References are written asrefs/heads/*。

aws iam get-policy-version --policy-arn arn:aws:iam::111122223333:policy/DenyChangesToMain \
  --version-id $(aws iam get-policy --policy-arn arn:aws:iam::111122223333:policy/DenyChangesToMain --query Policy.DefaultVersionId --output text)

Fix:add back"Null": {"codecommit:References": "false"}, use aws iam create-policy-version --set-as-defaultRelease a new version.

main can still be pushed directly

Troubleshooting:① Is the policy linked to the correct role/permission set? (aws sts get-caller-identityLook at the actual role)? ② Do you need to provision after changing the permission set? ③ResourceIs the region/account/repository name of the ARN correct (case sensitive)? ④ Whether it is writtenrefs/heads/master?

An error occurred (PullRequestApprovalRulesNotSatisfiedException) when calling the MergePullRequestBySquash operation

Reason:The approval rules were not met (this is the expected behavior).evaluate-pull-request-approval-rulesSee which rules are not met; confirm that the approver's identity ARN matches the pool member.

InvalidApprovalRuleTemplateContentException

Reason:JSON escaping errors,Version No 2018-11-08, branch name starts with*begins, or the content exceeds 3000 characters. It is recommended to write the content into a file and then use it"$(cat rule.json)"incoming.

test-repository-triggers returns failedExecutions

Reason:SNS is a FIFO topic (not supported), the topic is in a different region, or the Lambda resource policy does not allow itcodecommit.amazonaws.comcall.

Command line operation questions
1. Check which approval rule templates are associated with the repository myapp.
aws codecommit list-associated-approval-rule-templates-for-repository --repository-name myapp
2. Use CloudTrail to check who recently executed PutFile on myapp.
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=PutFile \
  --query 'Events[].[EventTime,Username]' --output table
Scenario analysis questions
You need "main and release/* of all repositorys can only be merged through PR and need to be approved by 2 people; the CI role can push tags." How to design?

① A Deny strategy,Resource: *, References listrefs/heads/main and refs/heads/release/*(UseStringLikeIfExistsTo support wildcards) + Null conditions, it is linked to the developer permission set, not to the release/CI role; tag isrefs/tags/*Not in the list, CI can push. ② An approval rule template, DestinationReferences is main andrefs/heads/release/*, 2 people, associate all repositorys in batches; when a new repository is created, it is automatically associated with the template (EventBridge + Lambda). ③ Alert for override events.

Instructional video

No verified special video on CodeCommit branch protection/approval rules was found. Please refer to official documents and storyboards.

Official documentation

Video storyboard (approx. 75 seconds)

Shot 1 · 0–20s
Screen: The developer pushes main, the IAM balance lights up red Deny, and the terminal displays 403.
Narrator: CodeCommit protects branches with IAM deny policies, and the condition key is codecommit colon References.
Shot 2 · 20–40s
Screen: Two requests, one without References key and one with it. Both turn red when the Null condition is removed.
Narrator: Be sure to add Null conditions, otherwise the push of all branches will be rejected.
Shot 3 · 40–75s
Screen: The PR card shows "Approved 1/2", and the merge button lights up after the second reviewer approves.
Narrator: The approval rule template only covers PR merging, not direct push, so it needs to be used together with the IAM policy.
or score ≥ 70% on the Quiz

Module 4 · CodeConnections: Connecting GitHub/GitLab repositories to AWS

21:00 – 28:00 · Without moving the repository, AWS services such as CodePipeline and CodeBuild can also read GitHub/GitLab code - the connection is an "authorization", not a "copy"
7 minutesFormer CodeStar ConnectionsPENDING after CLI creation★★★★
learning objectives
  • Name the providers CodeConnections supports: Bitbucket, GitHub / GitHub Enterprise Cloud, GitHub Enterprise Server, GitLab.com, GitLab Self-Managed, Azure DevOps; and when you need ithostresources.
  • Understanding connection statusPENDING → AVAILABLE(fails asERROR): Connections created by CLI/CloudFormation must complete the OAuth handshake in the console.
  • distinguish codeconnections:UseConnection(service role uses connection) withPassConnection(Give the connection ARN to the service), will useFullRepositoryIdWait for condition keys to narrow permissions; know the old and new prefixescodeconnections / codestar-connectionsdifference.
Prerequisite knowledge:OAuth application authorization concepts; Lesson 3 GitHub App.Importance:★★★★

What: What is the connection?

AWS CodeConnections(Developer Tools Console → Settings → Connections) is an AWS resource that holds AWS authorization to a third-party Git provider (such as the "AWS Connector for GitHub" app installed on GitHub, or an OAuth app authorized on GitLab). CodePipeline source operations (CodeStarSourceConnection), CodeBuild, CloudFormation Git synchronization, Amazon Q Developer and other services reference its ARN to pull code and write back status. It will be launched in 2024 byAWS CodeStar ConnectionsRenamed from: 2024-07-01 The connection ARN created by the console is usedarn:aws:codeconnections:…, oldcodestar-connectionsPrefix resources and actions are still available.

providerNeed host resources?Remarks
GitHub / GitHub Enterprise CloudNoInstall the AWS Connector for GitHub App
GitHub Enterprise ServerYesCan be placed within a VPC (codeconnections:VpcIdcondition key)
GitLab.comNoOAuth authorization; the creator needs to haveOwnerRole (repositories in a group do not require group Owner)
GitLab Self-ManagedYesRequires personal access token (api scope) to register host
Bitbucket CloudNoInstall app
Azure DevOpsNoNewer supported providers, details are subject to documentation

Why: Why not use PAT / Webhook directly?

  • Do not store long-term tokens in AWS:Tokens are hosted and rotated by the connection service, and the pipeline definition only references the ARN.
  • IAM controllable: Who can use which connection, access which repository, read-only or read-write, can all be expressed using IAM condition keys.
  • event driven: CodePipeline V2 can be triggered based on push, PR, and tags, without the need to maintain Webhooks yourself.
NoteThe official statement states that "the connection only provides access to the account that created and authorized the connection." If the authorizer leaves the company or loses permission in GitLab, the connection will become invalid (the status will change to ERROR or the pull will fail). Use a dedicated service account (robot user in GitLab) for authorization in production.

How: life cycle

  1. CreateConnection(Console, CLI, CloudFormation) → StatusPENDING。
  2. "Update pending connections" in the console: Jump to provider login → Authorize/Install application → Return → StatusAVAILABLE. This step requires handshake class permissions:StartOAuthHandshake、GetInstallationUrl、ListInstallationTargets、UpdateConnectionInstallation、GetIndividualAccessToken(These are "IAM permissions only", not API actions).
  3. When creating/updating a pipeline, the operator needs toPassConnection(condition keycodeconnections:PassedToService, such ascodepipeline.amazonaws.com)。
  4. When the pipeline is running,service roleneed UseConnection(availableFullRepositoryId、BranchName、ProviderPermissionsRequired、ProviderActionWait for the condition key to narrow).
  5. when no longer in useDeleteConnection, and uninstall the application/revoke OAuth authorization on the provider side.

When: Connection vs Mirroring

demandCodeConnectionsPush the image to CodeCommit (M7)
CodePipeline builds from GitHub/GitLab✓ First choiceYes, but one more hop delay
Reading code in AWS internal environment without public network✗(Pulled from the service side, not used by your VPC)✓ Works with VPC endpoints
There are still replicas in AWS when the provider goes down✗✓
Don't want to keep a copy of your code in AWS✓✗
Common misunderstandings① "You can use it after the CLI is successfully created" - the connection created by CLI/CloudFormation isPENDING, must go to the console to complete the handshake. ② "It is enough to give pipeline users UseConnection" - the runtime isservice roleWhile using the connection, the person creating the pipeline also needsPassConnection. ③ "The policy of codestar-connections can manage new connections" - the resource ARN prefix must match the service prefix in the policy.

Architecture diagram: CodePipeline reads GitLab repository through connection

GitLab.com acme/myappmain · MR · tags OAuth authorizationAuthorizer: mirror-bot (Owner)Can be revoked on the GitLab side AWS CodeConnections connection/abcd… ProviderType GitLab · AVAILABLE PENDING ─Handshake → AVAILABLEAuthorization expired → ERRORarn:aws:codeconnections:… CodePipeline V2Source: CodeStarSourceConnectionConnectionArn · FullRepositoryIdBranchName: main IAMCreated by PassConnectionService role: UseConnectionCondition FullRepositoryId=acme/myapp Runtime: CodePipeline calls the connection with the service role → the connection calls the GitLab API to pull the code on behalf of the authorized person
Figure 4-1 Code is not copied into the connection; the connection is just the "key" for authorization

Interaction: Connection state machine

Click the action buttons in sequence and watch how the status changes; try skipping the handshake and running the pipeline directly, or revoke authorization in GitLab.

(does not exist)
→
PENDING
→
AVAILABLE
/
ERROR
Start with create-connection.

Core commands and parameters

commandfunctionDescription
aws codeconnections create-connectionCreate connection--provider-type GitHub|GitLab|Bitbucket|GitHubEnterpriseServer|GitLabSelfManaged|AzureDevOps、--connection-name, self-management time--host-arn
aws codeconnections get-connectionView statusConnectionStatus:PENDING / AVAILABLE / ERROR
aws codeconnections list-connectionslist connections--provider-type-filter
aws codeconnections create-hostCreate a host for self-managed GitLab/GHES--provider-endpoint https://gitlab.example.com, optional--vpc-configuration
aws codeconnections delete-connectionDelete connectionRemember to revoke authorization on the provider side
aws codestar-connections …old prefix commandStill available for old resources
aws codeconnections create-connection --provider-type GitLab --connection-name gitlab-myapp \
  --profile cc-admin --region ca-central-1
aws codeconnections get-connection --connection-arn arn:aws:codeconnections:ca-central-1:111122223333:connection/aEXAMPLE-8aad-4d5d-8878-dfcab0bc441f \
  --query Connection.ConnectionStatus --output text
{
    "ConnectionArn": "arn:aws:codeconnections:ca-central-1:111122223333:connection/aEXAMPLE-8aad-4d5d-8878-dfcab0bc441f"
}
PENDING

Minimal permissions for the service role (only allowed to read acme/myapp)

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": "codeconnections:UseConnection",
    "Resource": "arn:aws:codeconnections:ca-central-1:111122223333:connection/aEXAMPLE-8aad-4d5d-8878-dfcab0bc441f",
    "Condition": {
      "StringEquals": {
        "codeconnections:FullRepositoryId": "acme/myapp",
        "codeconnections:ProviderPermissionsRequired": "read_only"
      }
    }
  }]
}

The operator creating the pipeline requires PassConnection

{
  "Effect": "Allow",
  "Action": "codeconnections:PassConnection",
  "Resource": "arn:aws:codeconnections:ca-central-1:111122223333:connection/*",
  "Condition": { "StringEquals": { "codeconnections:PassedToService": "codepipeline.amazonaws.com" } }
}

CodePipeline source operation fragment (only for illustration, see Lesson 5 for pipeline details)

{
  "name": "Source",
  "actionTypeId": { "category": "Source", "owner": "AWS", "provider": "CodeStarSourceConnection", "version": "1" },
  "configuration": {
    "ConnectionArn": "arn:aws:codeconnections:ca-central-1:111122223333:connection/aEXAMPLE-…",
    "FullRepositoryId": "acme/myapp",
    "BranchName": "main",
    "OutputArtifactFormat": "CODE_ZIP"
  },
  "outputArtifacts": [{ "name": "SourceOutput" }]
}

OutputArtifactFormatset toCODEBUILD_CLONE_REF, CodeBuild will do a complete git clone (which can rungit describeetc., requires the service role to have UseConnection), which is directly related to the topic of Lesson 5 "Shallow cloning causes git describe to fail".

Lab 4: Create a GitLab connection and complete the handshake (~5 minutes)

First build the project in GitLab(M5 will be officially built; if you are in a hurry, you can firstglab repo create alice-git-lab/myapp --private)。
CLI creates connection(See command paging), record the ARN, and confirm that the status isPENDING。
Console completes handshake: Developer Tools Console → Settings → Connections → Checkgitlab-myapp → Update pending connection→ Log in to GitLab →Authorize→ Return.
aws codeconnections get-connection --connection-arn "$CONN" --query 'Connection.[ConnectionName,ProviderType,ConnectionStatus,OwnerAccountId]' --output text
gitlab-myapp	GitLab	AVAILABLE	111122223333
(Optional) Verify permission boundaries: Create the simplest CodePipeline (Source in one step, or use the console wizard), do not give UseConnection to the service role first, and observe the source operation failure information; retry successfully after adding it. Delete the pipeline and its S3 artifact bucket when completed to avoid ongoing charges.
Cleanup (this module): If you do not do Lesson 5, executeaws codeconnections delete-connection --connection-arn "$CONN", and revoke AWS authorization in GitLab → User Settings → Applications → Authorized Applications.

Case 1: Authorizer resigned, all pipeline source stages failed

Question:On Monday morning all 40 pipelines failed in the Source stage.Root cause:The connection is authorized by the GitLab account of a retired engineer. The authorization becomes invalid after the account is disabled.Fix:Create a dedicated robot user (Owner/Maintainer for the relevant group), create a new connection and update the pipeline ARN in batches; record the "Connection Authorizer" in the runbook.

Case 2: A connection is shared by multiple teams and unauthorized reading occurs

Question:Team A’s pipeline can be pulled to Team B’s private repository.Root cause:The connection authorizer has the permissions of the entire group, and the UseConnection of the service role has no conditions.Fix:Service roles for each team pluscodeconnections:FullRepositoryIdConditions; or split connections and authorizers by team.

Case 3: Self-managed GitLab intranet

Method:forhttps://gitlab.corp.example.comCreate the host and configure the VPC (subnet, security group, TLS certificate), complete the host registration in GitLab with api-scoped PAT; usecodeconnections:VpcIdConditions restrict who can create a host.Limitations:The host setting requires the cooperation of the GitLab administrator, and the certificate chain must be complete.

Common errors and solutions

Connection arn:aws:codeconnections:… is not available / The connection is in PENDING state

Reason:The connection is still PENDING (no handshake after CLI/CloudFormation creation).Fix:Console Update pending connection.

… is not authorized to perform: codeconnections:UseConnection on resource …

Reason:The service role lacks UseConnection, or the condition keys (FullRepositoryId case, group path) do not match, or the policy writescodestar-connections:UseConnectionAnd the connection ARN iscodeconnectionsprefix.

aws codeconnections get-connection --connection-arn "$CONN" --query Connection.ConnectionArn
aws iam simulate-principal-policy --policy-source-arn arn:aws:iam::111122223333:role/PipelineRole \
  --action-names codeconnections:UseConnection --resource-arns "$CONN"
… is not authorized to perform: codeconnections:PassConnection

Reason:The IAM identity for the create/update pipeline is missing a PassConnection, orPassedToServiceCondition does not match.

Connection status ERROR

Reason:Authorization is revoked on the provider side, the application is uninstalled, and the authorizer loses access rights or is deleted.Fix:Re-update the connection (re-authorize) in the console, or create a new connection to replace it.

The pipeline cannot find the repository / Repository not found

Reason:FullRepositoryIdWrong writing (GitLab needs to write the complete path, including subgroupsacme/platform/myapp), or the authorized person does not have access rights to the project.

Command line operation questions
1. List all GitLab type connections in the account and their status.
aws codeconnections list-connections --provider-type-filter GitLab \
  --query 'Connections[].[ConnectionName,ConnectionStatus]' --output table
2. Create a host for self-managed GitLab.
aws codeconnections create-host --name corp-gitlab --provider-type GitLabSelfManaged \
  --provider-endpoint https://gitlab.corp.example.com
Scenario analysis questions
The security team requires: "No GitLab personal access tokens must appear in AWS, and the pipeline can only read the specified repository." How do you satisfy it?

Use CodeConnections (GitLab.com uses OAuth authorization and does not need to save PAT in AWS; the token is hosted by the connection service), and the authorizer is a dedicated robot account; the UseConnection of the service role is addedFullRepositoryId with ProviderPermissionsRequired=read_onlyConditions; only give the platform team CreateConnection and handshake permissions; regularly check the connection status and authorizer. Self-managed GitLab host registration requires PAT, but this PAT is only used during registration and can be revoked/rotated after registration (subject to the host requirements in official documents).

Instructional video

No verified CodeConnections feature video was found (there is still less dedicated explanation after the name change).

Official documentation

Video storyboard (approximately 60 seconds)

Shot 1 · 0–20s
Screen: CLI creates connection, status light yellow PENDING.
Narrator: The connection created by the command line is initially in a pending state and needs to complete the authorization handshake at the console.
Shot 2 · 20–40s
Screen: The browser jumps to the GitLab authorization page, click Authorize, and the status light turns green AVAILABLE.
Narrator: After authorization is complete, the connection is available.
Shot 3 · 40–60s
Screen: The assembly line character opens the door with the key (UseConnection), and it says acme/myapp read-only on the door.
Narrator: At runtime, the service role uses the connection and uses conditional keys to limit it to the specified repository.
or score ≥ 70% on the Quiz

Module 5 · GitLab: Projects, Protected Branches, and Merge Requests

28:00 – 37:00 · The group determines “who is a member”, the role determines “what can be done”, the protected branch determines “who can change main”, MR is the only front door
9 minutesProtected Branch: All plansLicensing by user/group: Premium★★★★★
learning objectives
  • Understand GitLab's group/subgroup/project hierarchy and six roles (Guest, Planner, Reporter, Developer, Maintainer, Owner), and know the default differences between Developer and Maintainer on branches.
  • Configure a protected branch:Allowed to merge、Allowed to push and merge(No one / Developers + Maintainers / Maintainers / Deployment Key),Allowed to force push, wildcard rules and "the loosest rule takes effect".
  • Explain the complete link of push rejection: Gitaly reception → pre-receive → Rails/internal/allowedAccess Check →remote: GitLab: You are not allowed to push code to protected branches on this project.
  • use glabComplete project construction, open MR, approve, merge, and be able to useglab apiConfigure protected branches.
Prerequisite knowledge:Lesson 2 Branching and Merging; Lesson 3 GitHub Rule Sets.Importance:★★★★★

What: Projects, Groups and Roles

A GitLab project includes a Git repository and MR, Issue, CI and other functions, and belongs to a namespace: personal namespace orgroup(group, nestable subgroups). The roles members gain on the group willinheritanceto subgroups and projects below it; members can also be invited individually on projects.

roleTypical permissions associated with repositories
GuestCode cannot be read in private projects (you can view Issues, etc.)
PlannerPlanning functions (Issue, Epic), not code-oriented (new in GitLab 17.7)
ReporterRead code, clone, pull; cannot push
Developerpush toNot protectedBranch, create MR; protected branches depend on rules
MaintainerManage protected branches, push rules, images, members (excluding Owner)
OwnerHighest permissions for groups/projects (delete, transfer, visibility, billing)

Why: What does a protected branch solve?

Without protection, any Developer cangit push --forceto main or delete it. The protected branch is inServerInterception: Who can push, who can merge through MR, whether it can be pushed, and whether it can be deleted (protected branches cannot be deleted through Git and must be unprotected first). When the default branch is created,Automatically protected, the default protection level can be adjusted in the Admin area (self-managed) or group settings.

How: Fields and semantics of rules

OptionsOptional valuemeaning
Branchname or wildcard likemain、release/*、*-stableCase sensitive; when multiple rules match the same branchThe most lenient takes effect
Allowed to mergeNo one / Developers + Maintainers / Maintainers (Premium can add specific users/groups)Who can click "Merge" in MR to make changes into this branch?
Allowed to push and mergeNo one / Developers + Maintainers / Maintainers / Deployment key (Premium can add users/groups)who canDirect git push(Can also be merged)
Allowed to force pushon/offAfter it is turned on, anyone with push permission can force push
Require approval from code ownersOn/off (Premium)MR requires approval from the code owner andRefuse to push directlyMatching branch (M6)

Access level values in the API:0 = No access(No one),30 = Developer,40 = Maintainer,60= Admin (self-managed instance administrator).

push internal link rejected

  1. client git pushReached via HTTPS (Workhorse) or SSH (gitlab-shell)Gitaly, the latter runsgit receive-packReceive object.
  2. Executed before updating refpre-receiveHook, Gitaly carries "old SHA, new SHA, ref name, user, protocol" to call GitLab Rails' internal APIPOST /api/v4/internal/allowed。
  3. Rails does access checks in turn: project permissions →protected branch(Push/Force/Delete)→Push rules(Premium) → File size/LFS integrity → Confidential push protection (Ultimate), etc.
  4. Any check fails → returnstatus: falseWith messages, Gitaly lets pre-receive exit non-zero, refNot updated(The object may have been uploaded but discarded).
  5. Client printingremote: GitLab: … with ! [remote rejected] main -> main (pre-receive hook declined)。

Key settings for Merge Request

Settings (Project → Settings → Merge Requests)Options
Merge methodMerge commit / Merge commit with semi-linear history / Fast-forward merge
Squeeze commits (squash)Do not allow / Allow / Encourage / Require
merge checkPipeline must be successful, all discussions must be resolved, (Premium) requires approval
Delete source branch by defaulton/off

When: Common configuration templates

branchAllowed to mergeAllowed to push and mergeForce push
mainDevelopers + Maintainers (with approval) or MaintainersNo oneclose
release/*MaintainersNo oneclose
env/production(Pushed by CI)No oneDeployment key/botclose

Compare to Lesson 3

GitLab protected branchesGitHub rulesetAzure Repos branching strategyCodeCommit
reject message“You are not allowed to push code to protected branches on this project.”“GH013: Repository rule violations found”“TF402455: Pushes to this branch are not permitted”HTTP 403 (no explanation)
bypassRoles/users in Allowed to push and mergeBypass list"Bypass policy" permissionsDeny’s identity is not listed
Common misunderstandings① "Maintainer is also restricted by No one, so no one can change main" - Yes, no one can push it directly, but the characters in Allowed to merge can still be merged through MR; this is exactly the desired effect. ② "Add one more*Rules set to Maintainers will be more stringent" - when there are multiple rulesloosesttakes effect, it may actually relax main. ③ "Protected branches can prevent MR from merging unapproved code" - not available in Free, and requires the necessary approval of Premium.

Timing diagram: push to protected branch rejected

git push Workhorse / shell Gitaly pre-receive Rails access checks ① Authentication (PAT/OAuth/SSH) ② receive-pack: refs/heads/main old → new ③ Execute hook before updating ref ④ POST /internal/allowed Protected branch main:push = No one → reject ⑤ status:false + message ⑥ remote: GitLab: You are not allowed to push code to protected branches on this project. ! [remote rejected] main -> main (pre-receive hook declined) —— ref unchanged
Figure 5-1 Rejection occurs in the pre-receive phase, and the reason is given by Rails’ access check

Structure diagram: Rule matching and "most relaxed effect"

Branch release/2.0Matching rule A: release/*Matching rule B: *Take the union (most relaxed) A: push=No one, merge=Maintainersstrict B: push=Developers+MaintainersLoose Result: Developer can push directlyRule B cancels out Rule A
Figure 5-2 Don’t use broad wildcard rules to “cover the truth”

Core Animation: GitLab protected branch rejects push process

Select the pusher role, target branch and push method, and gradually observe the process of the request going through Workhorse → Gitaly → pre-receive → Rails access check.

Ready.
$ git push gitlab main

Core commands and parameters

commandfunctionKey parameters
glab repo createCreate projectGROUP/NAME --private --defaultBranch main --description
glab mr createCreate MR--source-branch --target-branch main --title --description --fill --squash-before-merge --remove-source-branch
glab mr list / view / diffView MR--state opened
glab mr approve / revokeApprove / WithdrawMR number
glab mr mergemerge--squash --remove-source-branch --auto-merge(Automatically merged after pipeline success)
glab apiCall REST API-X POST projects/:id/protected_branches -f name=main -f push_access_level=0 -f merge_access_level=40
git push -o merge_request.createCreate MR when pushing (push options)-o merge_request.target=main -o merge_request.remove_source_branch
cd ~/git-lab/myapp
glab repo create alice-git-lab/myapp --private --defaultBranch main --description "Git course lab"
git remote add gitlab https://gitlab.com/alice-git-lab/myapp.git
git push gitlab main && git push gitlab --tags

# The default branch has been automatically protected, first look at the current rules (the project path requires URL encoding)
glab api "projects/alice-git-lab%2Fmyapp/protected_branches"
[{"id":101,"name":"main",
  "push_access_levels":[{"access_level":40,"access_level_description":"Maintainers"}],
  "merge_access_levels":[{"access_level":40,"access_level_description":"Maintainers"}],
  "allow_force_push":false,"code_owner_approval_required":false}]

Change to "No one can push directly, Developer + Maintainer can merge"

P="alice-git-lab%2Fmyapp"
glab api -X DELETE "projects/$P/protected_branches/main"
glab api -X POST "projects/$P/protected_branches" \
  -f name=main -f push_access_level=0 -f merge_access_level=30 -F allow_force_push=false
glab api -X POST "projects/$P/protected_branches" \
  -f name='release/*' -f push_access_level=0 -f merge_access_level=40

Can also be usedPATCH projects/:id/protected_branches/mainModifyallow_force_push、code_owner_approval_required;When modifying the access level list, PATCH needs to be passedallowed_to_push[]Waiting for array parameters, deleting and rebuilding is more intuitive. UI path: Project → Settings → Repository → Protected Branch.

MR whole process

git switch docs/adr-hosting
git push -u gitlab docs/adr-hosting
glab mr create --target-branch main --fill --remove-source-branch --squash-before-merge --yes
glab mr list
glab mr merge 1 --squash --remove-source-branch --yes
git switch main && git pull gitlab main
Creating merge request for docs/adr-hosting into main in alice-git-lab/myapp
!1 docs: ADR 0004 hosting decision (docs/adr-hosting)
 https://gitlab.com/alice-git-lab/myapp/-/merge_requests/1
✓ Squashed and merged!
✓ Deleted source branch docs/adr-hosting

Lab 5: Protect main and merge only via MR (~8 minutes)

Create project and push(first half of command pagination); confirm that the item visibility is Private on the web page.
Configure protected branches: main is push=No one, merge=Developers+Maintainers, and forced push is prohibited.
Verification direct push rejected(even if you are Owner/Maintainer)
git switch main
git commit --allow-empty -m "test: direct push"
git push gitlab main
remote: GitLab: You are not allowed to push code to protected branches on this project.
To https://gitlab.com/alice-git-lab/myapp.git
 ! [remote rejected] main -> main (pre-receive hook declined)
error: failed to push some refs to 'https://gitlab.com/alice-git-lab/myapp.git'
Verify push and delete
git push gitlab +main # push
git push gitlab --delete main # Delete

Both will be rejected; deleting a protected branch message is different from pushing (protected branches can only be unprotected and then deleted on the web). Record the original text you saw.

Change test commit to MR
git switch -c test/m5 && git push -u gitlab test/m5 \
  -o merge_request.create -o merge_request.target=main -o merge_request.remove_source_branch
glab mr merge --squash --yes
git switch main && git reset --hard gitlab/main && git pull gitlab main
(Optional) Invite the second account as Developer, use it to verify: the feature branch can be pushed, MR can be created, and cannot be merged when merge=Maintainers.

Case 1: Wildcard rules accidentally relaxed main

Question:In order for developers to promotefeature/*, someone added one*Rule (push=Developers+Maintainers), the result main can also be pushed directly.Root cause:The loosest one takes effect when multiple rules match.Fix:Delete *Rules (unprotected branches are inherently allowed to be pushed by Developer).

Case 2: CI needs to push version labels and changelog

Question:To publish a job, you need to push a "bump version" commit to main.Method:Preferred: Change to automatic merging via MR (glab mr create+ automatic merge); use when pushing directlydeployment keyOr project access token bot and include only that deployment key in Allowed to push and merge of the protected branch.Limitations:Per-user/group licensing requires Premium; deployment key option is available in Free (subject to interface).

Case 3: Unified protection rules for large organizations

Method:PremiumGroup-level protected branches(Top-level group only, Owner required) Protect main uniformly for all projects; Self-Managed sets the default branch protection level in the Admin area.Effect:New project creation is compliant.

Common errors and solutions

remote: GitLab: You are not allowed to push code to protected branches on this project.

Reason:The target branch is protected and your role is not among Allowed to push and merge.Fix:Push to a new branch and create MR; if you really need to push directly, please adjust the rules in Maintainer (it is not recommended to adjust main).

glab api "projects/GROUP%2FPROJECT/protected_branches/main" | python3 -m json.tool
remote: GitLab: You are not allowed to force push code to a protected branch on this project.

Reason:The rule is not enabled Allowed to force push.Fix:use git revertInstead of rewriting history; please rebase first if local rebase is out of date.git pull --rebase。

remote: You are not allowed to push code to this project. / 403

Reason:It is not a protected branch problem, but insufficient project permissions (Reporter/Guest), or lack of tokenswrite_repositoryScope, expired.

glab auth status
glab api "projects/GROUP%2FPROJECT/members/all/$(glab api user | python3 -c 'import sys,json;print(json.load(sys.stdin)["id"])')"
The "Merge" button on the MR page is gray: You don't have permission to merge this merge request

Reason:Your role is not in Allowed to merge on the target branch, or the merge check failed (pipeline, unresolved discussions, insufficient approval). Check out the MR page for specific tips on merging blocks.

Command line operation questions
1. Protect with APIrelease/*: No one can push directly, only Maintainer can merge.
glab api -X POST "projects/GROUP%2FPROJECT/protected_branches" -f name='release/*' -f push_access_level=0 -f merge_access_level=40
2. While pushing the branch, create an MR with main as the target and delete the source branch after merging.
git push -u gitlab feature/x -o merge_request.create -o merge_request.target=main -o merge_request.remove_source_branch
Scenario analysis questions
Under the Free package, the team hopes that "main must go through MR and at least someone has seen it." To what extent can it be achieved?

Protected branch push=No one can force all changes to go to MR; merge=Maintainers can make the "merger" a gatekeeper (when the author is a Developer, it must be merged by the Maintainer, which is equivalent to one person review); turn on "The pipeline must succeed" and "All discussions must be resolved". However, Free cannot force "required number of approvers" and CODEOWNERS approval. If necessary, please upgrade to Premium or add custom checks in the pipeline.

Verified instructional videos

▶
Git for GitLab (Beginner's FULL COURSE) — Valentin Despa
English · Contains demos for creating projects, branches, and MRs on GitLab
▶
GitLab CI CD Tutorial for Beginners [Crash Course] — TechWorld with Nana
English · Focusing on CI, you can understand the relationship between MR and the assembly line (the details of the assembly line belong to Lesson 5)

Official documentation

Video storyboard (approx. 75 seconds)

Shot 1 · 0–20s
Screen: The developer pushes main, and the request goes through Workhorse and Gitaly.
Narrator: The push reaches Gitaly and the pre-receive hook is executed before the branch is updated.
Shot 2 · 20–45s
Screen: The hook asks Rails "allowed?", Rails checks the protected branch table and returns red false.
Narrator: Rails does access checks: protected branches, push rules, file size, and rejects any one that fails.
Shot 3 · 45–75s
Screen: The terminal displays the remote: GitLab rejection message; then the developer switches to MR and merges in green.
Narrator: Nothing has changed on the branch. The correct approach is to push to a new branch and create a merge request.
or score ≥ 70% on the Quiz

Module 6 · GitLab: Approval Rules, CODEOWNERS and Push Rules

37:00 – 44:00 · Approval rules determine “how many people can approve”, CODEOWNERS determines “who must approve”, and push rules determine “what kind of commits cannot come in at all”
7 minutesAll three require Premium/UltimateConfidential Push Protection: Ultimate★★★★
learning objectives
  • Configure project approval rules (required number of people, approvers, target branches) and approval settings (disable author approval, prohibit committer approval, prohibit modifying rules in MR, remove approval when new commits are made).
  • Writing CODEOWNERS: Find location (root directory →docs/ → .gitlab/, the first one found takes effect), the last match takes precedence,[Section] with ^[Optional]Syntax; works with "requires code owner approval" for protected branches.
  • Configure push rules: commit message regularity, branch name regularity, prohibit confidential files, file name regularity, maximum file size, reject unsigned commits, DCO; if you know "Prohibit confidential files", only seefile name, content detection is the ultimate confidential push protection.
Prerequisite knowledge:M5 Protected Branches; Lesson 3 GitHub CODEOWNERS.Importance:★★★★

What: The action points of the three mechanisms

mechanismTiming of actionPackagefailure performance
Approval rulesMR mergePremium/Ultimate (Free only has optional approval, anyone can "approve" but it is not mandatory)MR shows "N approvals required" and the merge button is unavailable
CODEOWNERSWhen MR is merged ("code owner" approval rules are automatically generated); direct push is also refused after "requires code owner approval" is turned onPremium / UltimatePending approvals listed in MR for each segment owner
Push rulesWhen git push (pre-receive, the same link of M5)Premium / Ultimateremote: GitLab: … + pre-receive hook declined
Confidential push protectionScan key pattern by content when git pushUltimatePush is blocked and gives hit commits with files

Approval rules and settings

  • rules: Name, number of approvals required (0 = optional rule), approver (user/group), applicable target branch (all or one of the protected branches). There can be multiple entries, and they can only be merged if all are satisfied.
  • settings(Project → Settings → Merge Requests → Approvals):Disable MR creator approval(The default author is not included in the calculation),Disable committer approval(allowed by default, recommended to be turned on),Disable editing of approval rules in MR, remove all approvals or only remove affected code owner approvals when pushing new commits, require re-certification when approving, etc.

CODEOWNERS

  • Position (search in order, the first one found takes effect, the rest are ignored):./CODEOWNERS → ./docs/CODEOWNERS → ./.gitlab/CODEOWNERS. Press MRtarget branchFile version evaluation on.
  • The mode is similar to gitignore;The last matching entry takes effect, so*The default owner is written first.
  • Section:[Docs]Start a segment, each segment is calculated independently (each segment requires approval by an owner);[Docs][2]Requires approval of 2 people for this paragraph;^[Docs]It is an optional section (not mandatory); the default owner can be written after the section name.[Docs] @docs-team。
  • The owner can be@user、@group、@group/subgroup, email, or role (such as@@maintainer, subject to the document). The owner must have access to the project to be valid.
  • wantforceCode Owner Approval: Protect the target branch and open itRequire approval from code owners. Note: Users in Allowed to push and merge can still push directly to bypass MR, so main's push should be set to No one.

Push rules (Project → Settings → Repository → Push rules)

CategoryrulesExample
User verificationReject unverified users, reject inconsistent user names, check whether the author is a GitLab user, and author email regularity@example\.com$
Commit messageMust match / must not match regular^(feat|fix|docs|chore|refactor|test)(\(.+\))?: .+
branch nameBranch name regularity^(main|release/.+|(feature|fix|docs)/[a-z0-9._-]+)$
Prevent misuseReject unsigned commits and prohibit using git push to delete tags—
FileDisable pushing confidential files, Prohibited file name regularization, maximum file size (MB)(\.tfstate|\.env)$、10
DCOrefuse to lackSigned-off-by:commitgit commit -s

"Prohibit pushing confidential files"Maintained by GitLabfiles_denylist.yml, pressFile name/pathMatches: AWS credential files (such as.aws/credentials), various SSH private keys (id_rsa、id_ed25519and_skvariant), with.pem、.key、.history、_historyEnding files etc. itDo not check file contents——Lesson 1 Practice Repositoryconfig.envinsideFAKE_SECRET=...You won't be stopped by it; per-content detection requires Ultimate's secret push protection, or pre-commit/gitleaks on the client (Lesson 5).

Push rules only checkNew pushThe commit does not trace the existing history; the new project inherits the push rules of the group/instance, and the existing project needs to be updated manually.

When: Recommended combination

targetConfiguration
main must be reviewed by at least 2 people, and the security directory must be approved by the security teamApproval rule “Default” 2 people + CODEOWNERS[Security] /auth/ @acme/security+ Protected branches enable code owner approval
Conventional CommitsPush rule commit message regularity (mandatory on the server side), client commit-msg hook prompts in advance
Prevent private keys and status files from entering the repositoryBan confidential files + regular file names\.tfstate$+ maximum file size
Common misunderstandings① "If you turn on the prohibition of confidential files, the key will not be leaked" - it only looks at the file name. ② "CODEOWNERS can be placed in any directory" - only three locations are recognized, and only the first one found is used. ③ "Approval by the author himself counts" - Approval by the MR creator is prohibited by default; howevercommitter(People who have added commits to other people's MRs) can approve by default. It is recommended to turn on "Prohibit committer approval".

Decision diagram: Can MR be merged?

MR !7 → mainChanged /auth, /docs Approval rules DefaultRequired 2 · Approved 2 ✓ Code Owner [Security]/auth/ @acme/security · 0/1 ✗ Code Owner ^[Docs]Optional section · non-blocking Other merge checksPipeline success ✓Discussion resolved ✓Merger is in Allowed to merge ✓ prevent mergeWaiting for security team approval
Figure 6-1 All required rules (including each non-optional CODEOWNERS section) must be met to merge

Comparison Chart: Push Rules and Confidential Push Protection

Push: id_rsa, config.env, app.pyconfig.env content: FAKE_SECRET=...app.py content: AKIA… (fake AWS key) Push rules: Confidential files prohibited (Premium)id_rsa → deny(filename hit)config.env/app.py → ReleaseJust look at the name Confidential Push Protection (Ultimate)Scan new content for known key patternsAKIA… → BlockCustomized FAKE_SECRET may not hit
Figure 6-2 File name rules and content scanning are two different layers of protection

Interactive: MR Approval Calculator

Check the path of the MR change and the approved person, the calculator will parse the CODEOWNERS according to "Last matching takes effect", and determine whether it can be merged based on the project approval rules and settings.

* @alice @bob
[Security]
/app/auth/ @acme/security
[Infra][2]
/compose.yaml @carol @dave @erin
^[Docs]
/docs/ @frank
changed files
Approved(Author: alice)

Core commands (GitLab REST API, called via glab api)

endpointfunctionCommon fields
POST projects/:id/approval_rulesCreate new approval rulesname、approvals_required、user_ids[]、group_ids[]、protected_branch_ids[]
POST projects/:id/approvalsApproval settingsmerge_requests_author_approval、merge_requests_disable_committers_approval、disable_overriding_approvers_per_merge_request、reset_approvals_on_push
GET projects/:id/merge_requests/:iid/approval_stateCheck the status of each MR ruleWith code owner rules
PATCH projects/:id/protected_branches/mainTurn on code owner approvalcode_owner_approval_required=true
POST/PUT projects/:id/push_ruleCreate/modify push rulescommit_message_regex、branch_name_regex、prevent_secrets、file_name_regex、max_file_size、deny_delete_tag、member_check、reject_unsigned_commits
P="alice-git-lab%2Fmyapp"
# Approval settings: neither the author nor the committer can approve; new push resets approval; changing rules in MR is prohibited
glab api -X POST "projects/$P/approvals" -F merge_requests_author_approval=false \
  -F merge_requests_disable_committers_approval=true -F reset_approvals_on_push=true \
  -F disable_overriding_approvers_per_merge_request=true
# Approval rules: 2 people
glab api -X POST "projects/$P/approval_rules" -f name=Default -F approvals_required=2
# Protected branches enable code owner approval
glab api -X PATCH "projects/$P/protected_branches/main" -F code_owner_approval_required=true

CODEOWNERS files

# Default owner (written first, later more specific entries override it)
* @alice-git-lab/maintainers

[Security]
/app/auth/ @alice-git-lab/security

[Infra][2]
/compose.yaml @carol @dave @erin
/Dockerfile @carol @dave @erin

^[Docs] @frank
/docs/

Push rules

glab api -X POST "projects/$P/push_rule" \
  -f commit_message_regex='^(feat|fix|docs|chore|refactor|test|ci)(\(.+\))?: .{1,72}' \
  -f branch_name_regex='^(main|release/.+|(feature|fix|docs|test)/[a-z0-9._-]+)$' \
  -F prevent_secrets=true -f file_name_regex='(\.tfstate|\.tfstate\.backup)$' \
  -F max_file_size=10 -F deny_delete_tag=true
glab api "projects/$P/push_rule"
{"id":55,"project_id":…,"commit_message_regex":"^(feat|fix|docs|chore|refactor|test|ci)(\\(.+\\))?: .{1,72}",
 "branch_name_regex":"^(main|release/.+|(feature|fix|docs|test)/[a-z0-9._-]+)$",
 "deny_delete_tag":true,"prevent_secrets":true,"max_file_size":10,…}

Calling these endpoints on the Free plan will return 403/404. Regular use RE2 syntax (backtracking and lookahead are not supported), please refer to the documentation.

Experiment 6: CODEOWNERS + push rules (about 7 minutes, requires Premium trial; Free can only do steps 1 and 5)

Add CODEOWNERS(Merge via MR since main is protected)
cd ~/git-lab/myapp && git switch main && git pull gitlab main
git switch -c chore/codeowners
mkdir -p .gitlab && printf '* @%s\n\n[Docs]\n/docs/ @%s\n' "$(glab api user | python3 -c 'import sys,json;print(json.load(sys.stdin)["username"])')" "$(glab api user | python3 -c 'import sys,json;print(json.load(sys.stdin)["username"])')" > .gitlab/CODEOWNERS
git add .gitlab/CODEOWNERS && git commit -m "chore: add CODEOWNERS"
git push -u gitlab chore/codeowners -o merge_request.create -o merge_request.target=main
Turn on approval settings and code owner approval(Command paging), merge the MR of CODEOWNERS (if you only have one account, set the approval number to 0 and turn off "Disable author approval" to complete the experiment, remember to change it back later).
Configure push rules and test commit messages
git switch -c test/push-rules
git commit --allow-empty -m "update stuff"
git push gitlab test/push-rules
remote: GitLab: Commit message does not follow the pattern '^(feat|fix|docs|chore|refactor|test|ci)(\(.+\))?: .{1,72}'
 ! [remote rejected] test/push-rules -> test/push-rules (pre-receive hook declined)
git commit --amend -m "test: verify push rules" && git push gitlab test/push-rules
Test bans confidential files and branch names
ssh-keygen -t ed25519 -f ./id_ed25519 -N '' -q
git add id_ed25519 && git commit -m "test: try to push a key"
git push gitlab test/push-rules # Rejected: file name hits confidential file list
git reset --hard HEAD~1 && rm -f id_ed25519 id_ed25519.pub
git push gitlab HEAD:Bad_Branch # Rejected: Branch name does not match

Try again to modifyconfig.envinFAKE_SECRET=...And push - push rulesNoIntercept (just look at the file name), which is why content scanning is needed.

clean up:git push gitlab --delete test/push-rules;When you do not plan to continue the Premium trial, note which settings will expire after the trial ends (approval rules, push rules, code owner approvals).

Case 1: CODEOWNERS were misplaced and security approval never took effect

Question:repository root directory and.gitlab/There is one CODEOWNERS below, and the team has been changing.gitlab/version below.Root cause:GitLab only uses the first one found (root directory first).Fix:Keep only one; use GitLab's CODEOWNERS to verify in CI (the MR page will prompt a syntax error) and check for duplicate files.

Case 2: Commit message regularity blocks merge commit

Question:After turning on Conventional Commits regular rules, some developers locallygit mergeThe resulting "Merge branch..." commit was rejected.Method:Use squash in MR and set squash commit message template; allowed in regex^Merge branch, or require local rebase.Inspiration:Use it before pushing the rules onlinegit log --format=%sRun through the history to estimate the impact.

Case 3: The “last gate” for private key leakage

Question:Developers mistakenlydeploy.pemJoin commit.Result:The "No Confidential Files" rule blocked the push (.pemsuffix).Follow-up:The team enabled both client-side gitleaks hooks and Ultimate’s secret push protection, overwriting keys in the file contents.

Common errors and solutions

remote: GitLab: Commit message does not follow the pattern '…'

Reason:This push is in progressany oneThe newly committed message does not match.Fix:Find non-compliant commits and rewrite them (only private branches that have not yet been merged).

git log --format='%h %s' gitlab/main..HEAD | grep -Ev '^[0-9a-f]+ (feat|fix|docs|chore|refactor|test|ci)(\(.+\))?: '
git rebase -i gitlab/main # Mark non-compliant commits as reword and rewrite messages one by one
remote: GitLab: File name … was prohibited by the pattern … / The file was recognized as confidential

Reason:The file name matches the confidential file list or file name regularity.Note:Even if a later commit deletes the file, as long as it is within the push rangeanyCommits containing it will still be rejected - those commits will need to be rewritten (git resetorgit rebase) instead of adding another delete commit.

remote: GitLab: File "…" is larger than the allowed size of 10 MiB

Reason:Push rule maximum file size (or instance-level cap).Fix:Switch to Git LFS (supported by GitLab), or move large files out of the repository; commits containing large files also need to be rewritten. M7 has detailed procedures.

MR shows “Code owners approval is required” but the listed owners are empty/invalid

Reason:The username/group in CODEOWNERS does not exist or does not have access rights to the project; the group needs to be invited to the project or a project parent group. MR pages and file browsers will flag invalid owners.

Command line operation questions
1. Check the status of each approval rule (including code owner) of MR !7.
glab api "projects/GROUP%2FPROJECT/merge_requests/7/approval_state" | python3 -m json.tool
2. Use push rules to prohibit pushing Terraform state files and limit single files to 5 MB.
glab api -X PUT "projects/GROUP%2FPROJECT/push_rule" -f file_name_regex='\.tfstate(\.backup)?$' -F max_file_size=5
Scenario analysis questions
Audit requirement: “Any change/app/auth/The code must be approved by one person from the security team, and the author cannot approve it himself; document changes are not blocked. "Write out the configuration.

Premium:.gitlab/CODEOWNERSin[Security] segment /app/auth/ @acme/security, the document uses optional sections^[Docs];main is protected (push=No one) and Require approval from code owners is turned on; in the approval settings, creator approval is prohibited, committer approval is prohibited, and rule editing in MR is prohibited; code owner approval (or all approvals) is removed when a new commit is pushed. ensure@acme/securityThe group has access to the project.

Instructional video

No verified GitLab CODEOWNERS / Push Rules feature video found. You can refer to the GitLab introductory course in the M5 video page.

Official documentation

Video storyboard (approx. 75 seconds)

Shot 1 · 0–25s
Screen: MR changed the auth and docs directories, scanned the CODEOWNERS file from bottom to top, and highlighted the last matching line.
Narrator: Code owners are determined by the last matching entry, each segment requires approval by an owner, and optional segments are non-blocking.
Shot 2 · 25–50s
Screen: Pushing id_rsa is blocked by the red gate; pushing the fake key in config.env, but the gate does not respond.
Narrator: It is forbidden to only look at the file name of confidential files, and content scanning relies on confidential push protection.
Shot 3 · 50–75s
Screen: The commit message "update stuff" was rejected and passed after being changed to "fix: ...".
Narrator: Push rules enforce unified commit specifications on the server side, and cooperate with client hooks to provide early reminders.
or score ≥ 70% on the Quiz

Module 7 · Cross-platform mirroring and troubleshooting practice

44:00 – 54:00 · The mirror only synchronizes Git references and objects; authentication, permissions, branch protection, large files, any error in any link will cause the mirror to "red"
10 minutesPush image: all packagesPull image: Premium★★★★★
learning objectives
  • Build GitLab → CodeCommit push image (dedicated IAM user + HTTPS Git credentials + minimum permissions), understand the update timing (push trigger, within 5 minutes; only mirror protected branches within 1 minute),Keep divergent refswith "mirror only protected branches".
  • Know the difference between pull image (Premium) and push image, as well as the principle of "a repository can only have one writing source".
  • Diagnosed by troubleshooting tree: CodeCommit 403, Credential Assistant conflict, GitLab protected branch rejection, large files/pushes too large, LFS support differences, mirror forks.
Prerequisite knowledge:M2–M6。Importance:★★★★★

What: Two images of GitLab

Push image (Push)Pull the image (Pull)
directionGitLab → External (CodeCommit, GitHub, another GitLab)External → GitLab
PackageFree / Premium / UltimatePremium / Ultimate
triggerWhen there is a push from the upstream; the administrator can force "immediate update". Synchronized within 5 minutes after push, within 1 minute when "Mirror only protected branches" is turned onScheduled polling (can be triggered by API)
CertificationUsername + password (token) or SSH public keyTongzuo
Fork processingDefaultCoverForked refs on the mirror; if Keep divergent refs is turned on, it will be retained and skipped, and the update will be marked as failed.Stop updating the branch when it is forked locally

Pushing the image is essentially a GitLab background execution similar togit push --force(by selected ref scope) to the target URL. Branches in the source that are "deleted after merging into the default branch" will be deleted from the mirror during the next push; branches with unmerged changes will be retained. GitLab Silent Mode disables image push and pull.

Why: Why mirror to CodeCommit

  • Builds or deployments in an AWS isolated network (no public network) require Read Code → CodeCommit + VPC interface endpoint.
  • Disaster recovery: If GitLab.com fails, there will still be a read replica in AWS.
  • Compliance: Requires CloudTrail auditing of “who read the code” within AWS accounts.

How: GitLab → CodeCommit Key points for pushing images (according to GitLab official steps)

  1. Created in AWSDedicated IAM user, the inline policy only allows Git pull/push actions to the target repository, and the ARN must beExplicitly include region and account。
  2. generated for this userHTTPS Git credentials(Not the IAM user ID, not the access key).
  3. GitLab Project → Settings → Repository → Mirror Repository: Fill in the URLhttps://git-codecommit.<Zone>.amazonaws.com/v1/repos/<Repository>, direction Push, authentication method "username and password", fill in Git credentials.
  4. GitLab recommends leaving CodeCommit checked"Mirror only protected branches” (push more frequently, faster).
  5. Click "Update Now", and when you see the time of "Last Successful Update", it is successful; if it fails, it will appear in red.errorTag, hover to see errors.
The "dual" of protectionThe mirror target should beHuman read only: Expand M3's Deny policy on CodeCommit to "Except for mirror robots, all identities cannot push any branches." Otherwise, if someone directly changes the mirror, the next synchronization will be overwritten (default) or cause the mirror to fail (Keep divergent refs). Note: Mirror RobotMustCan push main - don't hook DenyChangesToMain to it.

Platform difference quick check (most commonly used when troubleshooting)

ProjectCodeCommitGitLab.com
Git LFSNot supported(2026 Q1 roadmap project, as of 2026-11-15, the document has not been online)Supported (all plans)
single object/fileSingle blob ≤ 2 GB; console/API/CLI single file ≤ 6 MBMaximum file size for push rules or instance settings; there are platform restrictions on repository and push sizes (see GitLab.com settings documentation)
Number of citations pushed in a single push≤ 4,000 (total of creation, deletion, and update)Subject to platform restrictions
Decline push feedbackHTTP 403, no reason textremote: GitLab: …specific reasons
Authentication failed403 (Incorrect credentials behaves the same as insufficient permissions)401 / “HTTP Basic: Access denied”

How Credential Assistant Conflicts Occur

Git will ask in ordercredential.helperin listeachAssistant (system level → global → repository level accumulation). If you configured the AWS CLI Credential Assistant and there are otherosxkeychain(macOS Git default) or Git Credential Manager (Windows default):

  1. First push: AWS Assistant now calculates the signature password, and Git executes it after the push is successful.credential approve,allThe assistant saves this password - including the keychain.
  2. The signature expires after about 15 minutes. The keychain will be ranked first in the next push and the expired password will be returned directly →403;Git executioncredential rejectIt may recover later, or it may fail repeatedly.
  3. Fix: Configuring a CodeCommit host with URL scopeClearlist of helpers (nullhelper =), then add only the AWS Assistant; delete it from the keychaingit-codecommitentry. The best solution is to use git-remote-codecommit instead (without going through the credential helper).
Common misunderstandings① "Mirror will synchronize MR, Issue, and approval rules" - only Git references and objects will be synchronized. ② "CodeCommit 403 must be the wrong password" - it may also be that the IAM conditional policy rejects a certain branch; it can be distinguished by changing the identity of GRC and pushing the same branch. ③ "The mirror target is also protected by GitLab push rules" - push rules are only checked on the GitLab side; the protection of the target platform must be configured on the target platform.

Architecture diagram: GitLab main repository + CodeCommit read-only mirror

Developerfeature branch + MR GitLab.com alice-git-lab/myappmain protected: push=No oneApproval / CODEOWNERS / Push RulesMirror: Push · Mirror only protected branchesAuthentication: Git credentials (mirror-bot) CodeCommit ca-central-1 / myapp-mirrorIAM user gitlab-mirror-bot: GitPull + GitPushAll other identities: Deny GitPush (read-only)Notification rules: branches-and-tags-updatedNo LFS · blob ≤ 2 GB Private Subnet Builder / CodeBuildVPC endpoint git-codecommit · GRC + instance role ≤ 1 min git clone (read only) Only writing source: GitLabMirror target is read-only for humans, otherwise it will fork
Figure 7-1 Every component on a mirrored link is a potential point of failure

Flowchart: "Intermittent 403" due to Credential Assistant conflict

10:00 push successfulAWS Assistant generates signing password credential approveosxkeychain also saved it 10:30 push → 403The keychain first returns the expired password RepairClear helper by host / use GRC Diagnosis: git config --show-origin --get-all credential.helper; GIT_TRACE=1 to see which helper returns the password
Figure 7-2 "It can be used as soon as it is configured, but 403 occurs after a while." This is almost always the reason.

Interaction: push image synchronization simulator

Create events on the source (GitLab) and target (CodeCommit) and observe the results of the mirror in the two modes of "cover forked refs" and "Keep divergent refs".

GitLab (source)
CodeCommit (mirror)
Click the event button and then click "Mirror Sync".

Core commands

commandfunctionDescription
glab api -X POST projects/:id/remote_mirrorsCreate a push imageurl(Credentials can be embedded, URL encoding is required),enabled、only_protected_branches、keep_divergent_refs
glab api projects/:id/remote_mirrorsCheck image statusupdate_status、last_successful_update_at、last_error
glab api -X POST projects/:id/remote_mirrors/:mid/syncForce immediate synclimited by frequency
glab api -X PUT projects/:id/remote_mirrors/:midModification (including keep_divergent_refs)Keep divergent refs can only be modified through the API after creation
git config --show-origin --get-all credential.helperView all assistants and sourcesThe first step in troubleshooting conflicts
GIT_TRACE=1 GIT_CURL_VERBOSE=1 git …Output HTTP and helper call detailsNote that the output may contain tokens, do not send them out.
git count-objects -vH、git rev-list --objects --all | git cat-file --batch-checkFind a big dealSee below
git lfs ls-files / git lfs envLFS statusBasis for judging when the target does not support LFS

Create an image (API version, equivalent to interface operation)

aws codecommit create-repository --repository-name myapp-mirror --repository-description "Read-only mirror of GitLab" \
  --profile cc-admin --region ca-central-1
# M2 Experiment Step 3 has created gitlab-mirror-bot and MirrorPushOnly policies; generated Git credentials
read -r CCUSER CCPASS _ <<<"$(aws iam create-service-specific-credential --user-name gitlab-mirror-bot \
  --service-name codecommit.amazonaws.com --profile cc-admin \
  --query 'ServiceSpecificCredential.[ServiceUserName,ServicePassword,ServiceSpecificCredentialId]' --output text)"
ENC_PASS=$(python3 -c 'import sys,urllib.parse;print(urllib.parse.quote(sys.argv[1],safe=""))' "$CCPASS")
P="alice-git-lab%2Fmyapp"
glab api -X POST "projects/$P/remote_mirrors" \
  -f url="https://${CCUSER}:${ENC_PASS}@git-codecommit.ca-central-1.amazonaws.com/v1/repos/myapp-mirror" \
  -F enabled=true -F only_protected_branches=true -F keep_divergent_refs=false
unset CCPASS ENC_PASS
MID=$(glab api "projects/$P/remote_mirrors" | python3 -c 'import sys,json;print(json.load(sys.stdin)[0]["id"])')
glab api -X POST "projects/$P/remote_mirrors/$MID/sync"
sleep 30; glab api "projects/$P/remote_mirrors/$MID" | python3 -m json.tool | grep -E 'url|update_status|last_successful|last_error'
    "url": "https://*****:*****@git-codecommit.ca-central-1.amazonaws.com/v1/repos/myapp-mirror",
    "update_status": "finished",
    "last_successful_update_at": "2026-11-15T10:42:07.000Z",
    "last_error": null,

The IAM policy of "read-only for humans" for the mirror target (attached to the developer permission set, not to the mirror robot)

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Deny",
    "Action": ["codecommit:GitPush","codecommit:PutFile","codecommit:DeleteFile","codecommit:DeleteBranch",
               "codecommit:CreateBranch","codecommit:MergeBranchesByFastForward","codecommit:MergeBranchesBySquash",
               "codecommit:MergeBranchesByThreeWay","codecommit:MergePullRequestByFastForward",
               "codecommit:MergePullRequestBySquash","codecommit:MergePullRequestByThreeWay"],
    "Resource": "arn:aws:codecommit:ca-central-1:111122223333:myapp-mirror"
  }]
}

All write operations to this repository are denied here, so there is no References condition (and therefore no Null condition).

Credential Assistant conflict fix (macOS example)

git config --show-origin --get-all credential.helper
# Delete cached CodeCommit entries in the keychain
git credential-osxkeychain erase <<'EOF'
protocol=https
host=git-codecommit.ca-central-1.amazonaws.com
EOF
# For CodeCommit hosts only: clear inherited helpers and use only AWS helpers (or simply use GRC instead)
git config --global credential.https://git-codecommit.ca-central-1.amazonaws.com.helper ''
git config --global --add credential.https://git-codecommit.ca-central-1.amazonaws.com.helper '!aws codecommit credential-helper $@'
git config --global credential.https://git-codecommit.ca-central-1.amazonaws.com.UseHttpPath true

Windows (GCM): Remove in Credential Manager → Windows Credentialsgit:https://git-codecommit…entry; Linux if configuredstore/cacheAssistant, also press the host to clear.

find big objects

git count-objects -vH
git rev-list --objects --all \
 | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' \
 | awk '$1=="blob" && $3 > 50*1024*1024 {printf "%.1f MB %s\n", $3/1048576, $4}' | sort -rn | head

Experiment 7: GitLab → CodeCommit push image + failure drill (about 9 minutes)

Create image(Command paging "Create Image"), confirmupdate_status: finished, and use the developer identity to clone the image to check the commit SHA of main.
git ls-remote gitlab refs/heads/main
git ls-remote codecommit::ca-central-1://cc-dev@myapp-mirror refs/heads/main

Both SHAs must be identical. Because only protected branches are mirrored, feature branches will not appear in the mirror.

Verify synchronization delay: Merge an MR into main in GitLab, time it, and the mirrored main should advance within 1 minute.
Troubleshooting 1: Invalid mirroring credentials
aws iam update-service-specific-credential --user-name gitlab-mirror-bot \
  --service-specific-credential-id ACCAXXXXXXXXXXXXXXXXX --status Inactive --profile cc-admin
glab api -X POST "projects/$P/remote_mirrors/$MID/sync"; sleep 30
glab api "projects/$P/remote_mirrors/$MID" | grep -E 'update_status|last_error'
"update_status": "failed",
"last_error": "… The requested URL returned error: 403 …",

Restore: Change status backActiveResync.

Troubleshooting 2: Someone pushed the image directly: First temporarily remove deny-mirror-writes from the developer permission set (or use administrator status), push a commit to the main of the CodeCommit mirror, then merge an MR in GitLab and synchronize: the commit on the mirror in default mode isCoverDisappear; open with APIkeep_divergent_refs=trueRepeatedly, the image update is marked as failed. After the walkthrough, restore the read-only policy and set keep_divergent_refs back to false.
Troubleshooting 3: GitLab Protected Branch Rejection: Use Developer status directlygit push gitlab main, compare with M5 message; do the same operation with CodeCommit image, and compare with 403. Experience the difference in feedback between the two platforms.
(Optional) LFS Difference: in a test branchgit lfs track "*.psd"Commit a file and push it to GitLab successfully; try to push it directly to the CodeCommit test repository and observe that the LFS upload fails (CodeCommit does not provide an LFS endpoint). Delete the test branch after the experiment and do not merge it into main, otherwise it will pollute the image.
interactive troubleshooting tree: Open the "Troubleshooting" tab and use the troubleshooting tree to review the above three faults.

Case 1: All images suddenly failed - there are slashes in the password

Question:After rotating Git credentials, the image reports "URL format error" or fails authentication.Root cause:The new password contains/、+、=, are treated as path delimiters when directly spelled into the URL.Fix:Fill in the "Password" field separately in the interface (without putting it in the URL), or URL-encode the password in the API.

Case 2: macOS developer “403s every once in a while”

Question:Half the team uses the AWS CLI Credential Assistant, pushing intermittent 403s.Root cause:osxkeychain caches expired signing passwords.Fix:Unified switch to git-remote-codecommit; workaround is to clear helper list by host and delete keychain entries. AWS troubleshooting documentation specifically describes this phenomenon.

Case 3: Mirror repository has more than 4000 references

Question:First time mirroring an old repository with 9000 tags to CodeCommit failed.Root cause:CodeCommit can push up to 4,000 citations at a time.Fix:Use the command line to push tags in batches for the first time (M8 batch script), and then enable the GitLab image for increments.

interactive troubleshooting tree

Work your way through the symptoms you see; each diagnosis provides commands and fixes.

Common error text

fatal: unable to access 'https://git-codecommit.…/v1/repos/…/': The requested URL returned error: 403

See the "CodeCommit 403" branch of the troubleshooting tree: first check the credential assistant, then check IAM (including conditional policy and SCP), and then check the region and repository name.

remote: HTTP Basic: Access denied. If a password was provided for Git authentication, the password was incorrect or you're required to use a token instead of a password.

GitLab authentication failed: Accounts with 2FA turned on must use a personal access token (scopewrite_repository) or OAuth (GCM/glab); it's the same message if the token expires or is revoked.

batch response: … / LFS: Repository or object not found (push to CodeCommit)

The target platform does not support LFS. Choice: keep the main repository on a platform that supports LFS; the repository mirrored to CodeCommit does not use LFS; or put large files on S3 while waiting for CodeCommit LFS to be officially launched.

error: RPC failed; HTTP 413 / remote end hung up unexpectedly (big push)

The push package is too large or exceeds the agent/platform limit. Push in batches (by commit range or branch), remove large files (Lesson 7git filter-repo), or use LFS instead (when supported by the target).

Command line operation questions
1. One command simultaneously compares whether all tags on the GitLab and CodeCommit images are consistent.
diff <(git ls-remote --tags gitlab | sort) <(git ls-remote --tags codecommit::ca-central-1://cc-dev@myapp-mirror | sort) && echo "tags in sync"
2. See which credential helper returned the password for CodeCommit.
GIT_TRACE=1 git ls-remote https://git-codecommit.ca-central-1.amazonaws.com/v1/repos/myapp 2>&1 | grep -i "credential"
Scenario analysis questions
The mirror shows "Last successful update" stopped 3 days ago, but no one gets the alert. How to fix it and prevent it from happening again?

View last_error: Commonly seen are Git credentials being deactivated/rotated, IAM policy changes (for example, someone hooked DenyChangesToMain to the mirror robot), the target repository being renamed, and the mirror target being forked (Keep divergent refs). Force synchronization after repair. Prevention: Use API check for scheduled jobslast_successful_update_atAn alarm occurs when the threshold is exceeded; CodeCommit uses notification rulesbranches-and-tags-updatedThe "absent" heartbeat is performed; the runbook is rotated according to the credentials, and the GitLab image configuration is updated synchronously.

Instructional video

No verified "GitLab Pushing Image to CodeCommit" feature video found.

Official documentation

Video storyboard (approx. 75 seconds)

Shot 1 · 0–25s
Screen: GitLab main moves forward, and after one minute the arrow pushes the commit to CodeCommit.
Narrator: Push mirroring is triggered when there is a push from the upstream, and is completed within one minute when only mirroring protected branches.
Shot 2 · 25–50s
Screen: Someone directly changed the CodeCommit main, and the commit was overwritten and disappeared during the next synchronization.
Narrator: Forked references are overwritten by default. Therefore, the mirror target must be read-only for humans.
Shot 3 · 50–75s
Image: The keychain icon hands over a rusty key and the CodeCommit door lights up with a 403.
Narrator: Intermittent 403s are often caused by the keychain caching expired signing passwords. Using git-remote-codecommit instead will not have this problem.
or score ≥ 70% on the Quiz

Module 8 · Migration, Costs and Self-Testing

54:00 – 60:00 · Git history can be moved with one command. The difficulty lies in PR/MR, permissions, pipelines and “the day of switching”
6 minutesgit push --mirrorCodeCommit single push ≤ 4000 citations★★★★
learning objectives
  • Planning a migration for GitHub / Azure Repos ↔ GitLab / CodeCommit: Git Data (clone --mirror+ Selective push) and platform data (importer) are processed separately to avoid hidden references and the 4000 reference limit.
  • Estimate CodeCommit costs (definition of active users, free credits, overage unit price) and compare GitLab plans.
  • Complete the self-assessment for this lesson.
Prerequisite knowledge:M1–M7; Lesson 3.Importance:★★★★

What: Two types of data to be migrated

dataHow to moveTools
Git references and objects (branch, tag, full history)git clone --mirror→ only pushrefs/heads/* with refs/tags/*Git itself
PR/MR, Review, Issue, Wiki, ReleasePlatform importer or APIGitLab's GitHub importer (migrate PR → MR, Issue, etc.); "Import repository through URL" only migrates Git data
LFS objectgit lfs fetch --all → git lfs push --allThe target must support LFS (CodeCommit does not support it as of verification date)
Permissions, branch protection, approval, CODEOWNERS semanticsReconfigure according to the target platform (comparison table of M3/M5/M6 in this lesson)IaC: gitlab/aws provider for Terraform
Pipeline, Webhook, IntegrationRebuild; switch to CodeConnections on AWS sideLesson 5

Why: Why not directlygit push --mirror

  • Hide reference: Cloning from the GitHub image will bringrefs/pull/*, which will be brought from GitLabrefs/merge-requests/*、refs/keep-around/*Wait. Pushing to the target may be rejected (GitHub refuses to update hidden references) or become a large number of garbage references in the target.
  • CodeCommit can push up to 4,000 citations in a single push: The old repository often has tens of thousands of labels and needs to be divided into batches.
  • protected branch: If the target has been configured with protection (for example, main push=No one), the first push will be rejected - push first, then protect.

How: Migration steps (general)

  1. Freeze window announcement; source repository set to read-only (GitHub archive, Azure Repos disabled repository, GitLab archive, CodeCommit with IAM Deny).
  2. git clone --mirrorSource repository; if LFS is available,git lfs fetch --all。
  3. Create an empty repository on the target,Not yetEnable branch protection and push rules (or allow migration accounts to bypass).
  4. push refs/heads/* with refs/tags/*(CodeCommit batches by ≤ 4000 references).
  5. Verification: number of branches/labels, consistent SHA of each branch,git fsck。
  6. Import platform data (importer), rebuild protection, approval, CODEOWNERS (CodeCommit has no CODEOWNERS, use approval rule template instead), Webhook/connection.
  7. Developer executiongit remote set-url origin …;The source repository remains read-only for a period of time or reverse mirrored for rollback.

CodeCommit cost

Projectcontent (withOfficial pricing pageshall prevail)
free tierEffective for new and old customers in the long term;Top 5 active usersFree (AWS public free quota is 50 GB storage, 10,000 Git requests per month; subject to pricing page)
additional active usersOfficial example: billing for 6 active users per month$1→ $1/month for each additional active user (additional storage and request quota included with each paid user are subject to the pricing page)
excessstorage $0.06/GB-month;Git request$0.001/time
active user definitionVisited the CodeCommit repository this monthEach unique AWS identity: IAM user/role, federated user, root account; access through Git, console, CLI, SDK all count;Identities used by services such as CodeBuild and CodePipeline also count;No visits during the month will not be billed
Related feesVPC interface endpoints (hourly + traffic), KMS customer-managed keys, CloudTrail data events, SNS, and more additional

GitLab Cost Highlights

  • GitLab.com Free: Free, but the private namespace has a limit on the number of members, storage and computing minute quotas; Premium/Ultimate is paid annually by seat (user), see about.gitlab.com/pricing for prices.
  • The approval rules, CODEOWNERS approval, push rules, and pull images used in this lesson require Premium; confidential push protection requires Ultimate.
  • Self-Managed: CE is free, but servers, backups, upgrades and labor are the main costs.
Common misunderstandings① "CodeCommit only calculates money based on the number of developers" - assembly line service roles, mirror robots, and cross-account roles are all active identities. ② "The importer will migrate branch protection" - the protection rules need to be rebuilt according to the semantics of the target platform. ③ "git push --mirroris the most complete migration" - it will also hide references and willDeleteReferences that do not exist in the source on the target are very dangerous when pointing to the wrong remote.

migration matrix

GitHubrefs/pull/* hide references Azure ReposPAT/GCM clone GitLabGitHub Importer/URL Import CodeCommit≤4000 citations/times · No LFS Importer (PR→MR, Issue) URL import (Git only) clone --mirror + push in batches Push image (M7) Must do after migrationRebuild branch protection / approval / CODEOWNERSUpdate CodeConnections/Webhooksgit remote set-url · Source repository read-only
Figure 8-1 Git data and platform data are migrated in two paths

Interactive: CodeCommit Monthly Cost Calculator

Enter the active identity and usage, and the calculator estimates based on "the first 5 active users are free, then $1/user, excess $0.06/GB-month, $0.001/time" (the limit is calculated based on AWS's public 50 GB, 10,000 times + 10 GB, 2,000 times per paid user, for estimation only, subject to the pricing page).




Click "Calculate".

Migration command

commandfunction
git clone --mirror URL repo.gitComplete naked clone (with all references)
git push TARGET 'refs/heads/*:refs/heads/*' 'refs/tags/*:refs/tags/*'Only push branches and tags to avoid hidden references
git for-each-ref --format='%(refname)' refs/tags | split -l 3000Split references by batch (CodeCommit ≤ 4000/time)
git lfs fetch --all / git lfs push --all TARGETMigrate LFS objects (must be supported by target)
glab repo create/GitLab import interfaceCreate a target project or use the importer
git remote set-url origin NEWDeveloper switches to remote

GitHub → CodeCommit (push tags in batches)

git clone --mirror https://github.com/acme/legacy-app.git legacy-app.git
cd legacy-app.git
git for-each-ref --format='%(refname)' refs/pull | wc -l # These will not be migrated
aws codecommit create-repository --repository-name legacy-app --profile cc-admin --region ca-central-1
TARGET=codecommit::ca-central-1://cc-admin@legacy-app
git push "$TARGET" 'refs/heads/*:refs/heads/*'
git for-each-ref --format='%(refname):%(refname)' refs/tags > tags.txt
split -l 3000 tags.txt tagbatch_
for f in tagbatch_*; do git push "$TARGET" $(cat "$f") || break; done
# Verification
diff <(git for-each-ref --format='%(objectname) %(refname)' refs/heads refs/tags | sort) \
     <(git ls-remote "$TARGET" | awk '{print $1" "$2}' | grep -v '\^{}' | sort) && echo "refs match"

Azure Repos → GitLab (Git data only)

git clone --mirror https://dev.azure.com/acme/Shop/_git/myapp myapp.git
glab repo create acme/myapp --private
cd myapp.git
git push https://gitlab.com/acme/myapp.git 'refs/heads/*:refs/heads/*' 'refs/tags/*:refs/tags/*'
# Press M5/M6 again to rebuild protected branches, approvals and CODEOWNERS

CodeCommit → GitLab/GitHub (Leave CodeCommit)

git clone --mirror codecommit::ca-central-1://cc-dev@myapp myapp-cc.git
cd myapp-cc.git
git push https://gitlab.com/acme/myapp.git 'refs/heads/*:refs/heads/*' 'refs/tags/*:refs/tags/*'
# CodeCommit's PRs and comments will not be migrated with Git; use aws codecommit get-pull-request / get-comments-for-pull-request to export the archive when needed

GitLab's "Import from GitHub" can migrate PR (→MR), Issues, comments, milestones, etc., and is suitable for GitHub → GitLab; the specific importable objects and requirements (token range, user mapping) are subject to the GitLab import document.

Lab 8: Migrate myapp from GitLab to a new CodeCommit repository and verify it (about 5 minutes)

Image clone and view hidden references
cd /tmp && git clone --mirror https://gitlab.com/alice-git-lab/myapp.git myapp-mig.git && cd myapp-mig.git
git for-each-ref --format='%(refname)' | sed -E 's#^(refs/[^/]+).*#\1#' | sort | uniq -c
      6 refs/heads
      3 refs/merge-requests
      2 refs/tags
Push only branches and tags
aws codecommit create-repository --repository-name myapp-migrated --profile cc-dev --region ca-central-1
git push codecommit::ca-central-1://cc-dev@myapp-migrated 'refs/heads/*:refs/heads/*' 'refs/tags/*:refs/tags/*'
Verify: Use diff in command paging to verify that all branches are consistent with the label SHA; thengit cloneone sharegit fsck --full。
cost estimate: Use the animated paginated calculator to estimate the monthly cost of CodeCommit based on your team size and service status. Write ADR 0004.
clean up:aws codecommit delete-repository --repository-name myapp-migrated;rm -rf /tmp/myapp-mig.git。

Case 1: 200 repositories moved from CodeCommit to GitLab (2024)

Method:Script traversallist-repositories, one by oneclone --mirror → glab repo create→ Push branches and tags → Verification → Hang Deny on CodeCommit and set the write policy to read-only; PR history is exported as JSON and stored in S3; CodePipeline uses CodeConnections instead.Lessons:The "implicit dependencies" that were not migrated were EventBridge rules and triggers (Lambda), which were exposed within a week after the switch.

Case 2: CODEOWNERS does not take effect after importing GitHub → GitLab

Question:GitHub.github/CODEOWNERSMigrated over as it is, but GitLab only recognizes the root directory,docs/、.gitlab/。Fix:move to.gitlab/CODEOWNERS, put the GitHub team name (@acme/team) is mapped to the GitLab group path and confirm that the group has been invited to the project; turn on code owner approval (Premium).

Case 3: CodeCommit billing appears for 40 active users

Question:The team is only 15 people, but the bill has 40 active users.Root cause:Each pipeline's CodeBuild/CodePipeline service role and multiple cross-account roles are counted as active identities.Optimization:Incorporate the Pipeline service role, or use CodeConnections instead to have Pipeline fetch code directly from GitLab (depending on overall cost).

Common errors and solutions

! [remote rejected] refs/pull/1/head -> refs/pull/1/head (deny updating a hidden ref)

Reason:use git push --mirrorPushed hidden refs to GitHub.Fix:push onlyrefs/heads/* with refs/tags/*。

An error occurs when pushing to CodeCommit (too many references, more than 4000 references in a single push)

Fix:Push labels in batches (≤ 3000); push branches first, then push labels in batches.

remote: GitLab: You are not allowed to push code to protected branches on this project. (when migration is first pushed)

Reason:The default branch of the target project is protected as soon as it is created, or group-level protection has taken effect.Fix:Use Maintainer to migrate accounts and temporarily allow push, or push first and then configure protection; the importer method is not affected by this.

After the migration, the developer git pull reported "fatal: refusing to merge unrelated histories"

Reason:The target repository was initialized before the README commit ("Initialize repository" was checked when creating the project).Fix:Rebuild the empty repository before pushing; do not merge irrelevant history on targets that already have history.

Command line operation questions
1. Count the number of references of each type in an image clone.
git for-each-ref --format='%(refname)' | cut -d/ -f1-2 | sort | uniq -c
2. Switch the origin of all developers from CodeCommit to GitLab (single repository).
git remote set-url origin https://gitlab.com/acme/myapp.git && git fetch origin && git branch -u origin/main main
Scenario analysis questions
The company is moving 30 Azure Repos repositorys to CodeCommit (an AWS-first strategy), 3 of which use LFS. Give a plan.

27 general repositorys:clone --mirror+ Push only branches and tags (in batches if necessary), replace Azure's minimum reviewer policy with an approval rule template on CodeCommit, replace "disable direct push" with IAM Deny, change build verification to EventBridge + CodeBuild write back PR; "Automatically include reviewers" in Azure has no corresponding function, and needs to be approximated by an approver pool. 3 LFS repositories: CodeCommit does not support LFS as of the date of verification. It is recommended to stay on a platform that supports LFS (or move to GitLab/GitHub) and use CodeConnections to connect to the AWS pipeline. It will be re-evaluated after CodeCommit LFS is officially launched (subject to the user guide). Costs are estimated based on active identities (including pipeline service roles).

Verified instructional videos

▶
Git and GitHub for Beginners - Crash Course — freeCodeCamp.org
English · Review remote, push and clone to lay the foundation for migration operations

No verified "Cross-Platform Repository Migration" feature video found.

Official documentation

Video storyboard (approximately 60 seconds)

Shot 1 · 0–20s
Screen: The image clone is expanded into three types of references: heads, tags, and pull, and pull is crossed out.
Narrator: Migration only pushes branches and tags, hidden references stay in place.
Shot 2 · 20–40s
Screen: Tens of thousands of tags are divided into 3,000 packages and pushed to CodeCommit one by one.
Narrator: CodeCommit can push up to 4,000 references at a time, and large repositorys need to be pushed in batches.
Shot 3 · 40–60s
Screen: There are several robot icons standing next to the developer's avatar on the bill.
Narrator: CodeCommit is billed on an active basis, including pipeline service roles.
or score ≥ 70% on the Quiz

Command cheat sheet

AWS CodeCommit · CodeConnections · GitLab · Mirroring and Migration · Every code block can be copied with one click
Reference after class

CodeCommit certification

aws configure sso --profile cc-dev && aws sso login --profile cc-dev
pipx install git-remote-codecommit
git clone codecommit::ca-central-1://cc-dev@myapp
git remote add cc codecommit://cc-dev@myapp
aws iam create-service-specific-credential --user-name U --service-name codecommit.amazonaws.com
aws iam update-service-specific-credential --user-name U --service-specific-credential-id ID --status Inactive
aws iam upload-ssh-public-key --user-name U --ssh-public-key-body file://~/.ssh/codecommit_rsa.pub
ssh git-codecommit.ca-central-1.amazonaws.com

CodeCommit repository and PR

aws codecommit create-repository --repository-name R --repository-description D
aws codecommit get-repository --repository-name R
aws codecommit list-branches --repository-name R
aws codecommit update-default-branch --repository-name R --default-branch-name main
aws codecommit create-pull-request --title T --targets repositoryName=R,sourceReference=feat,destinationReference=main
aws codecommit update-pull-request-approval-state --pull-request-id N --revision-id REV --approval-state APPROVE
aws codecommit evaluate-pull-request-approval-rules --pull-request-id N --revision-id REV
aws codecommit merge-pull-request-by-squash --pull-request-id N --repository-name R
aws codecommit delete-repository --repository-name R

CodeCommit protection and notifications

# IAM Deny: codecommit:GitPush/PutFile/DeleteFile/DeleteBranch/Merge*
#   StringEqualsIfExists codecommit:References [refs/heads/main]
#   Null codecommit:References "false"
aws codecommit create-approval-rule-template --approval-rule-template-name N \
  --approval-rule-template-content '{"Version":"2018-11-08","DestinationReferences":["refs/heads/main"],"Statements":[{"Type":"Approvers","NumberOfApprovalsNeeded":2,"ApprovalPoolMembers":["arn:aws:sts::ACCT:assumed-role/ROLE/*"]}]}'
aws codecommit associate-approval-rule-template-with-repository --approval-rule-template-name N --repository-name R
aws codecommit put-repository-triggers --cli-input-json file://trigger.json
aws codestar-notifications create-notification-rule --name N --resource ARN --detail-type FULL \
  --event-type-ids codecommit-repository-pull-request-created --targets TargetType=SNS,TargetAddress=TOPIC

CodeConnections

aws codeconnections create-connection --provider-type GitLab --connection-name N # → PENDING
# Console: Settings → Connections → Update pending connection → AVAILABLE
aws codeconnections get-connection --connection-arn ARN --query Connection.ConnectionStatus
aws codeconnections list-connections --provider-type-filter GitHub
aws codeconnections create-host --name H --provider-type GitLabSelfManaged --provider-endpoint https://gitlab.corp
aws codeconnections delete-connection --connection-arn ARN
# IAM: Service role UseConnection (FullRepositoryId condition); Creator PassConnection (PassedToService)

GitLab projects, protected branches, and MR

glab auth login --hostname gitlab.com && glab auth status
glab repo create GROUP/NAME --private --defaultBranch main
glab api "projects/GROUP%2FNAME/protected_branches"
glab api -X POST "projects/GROUP%2FNAME/protected_branches" -f name=main -f push_access_level=0 -f merge_access_level=30
# Access level: 0=No one 30=Developer 40=Maintainer 60=Admin
git push -u gitlab feat -o merge_request.create -o merge_request.target=main -o merge_request.remove_source_branch
glab mr create --target-branch main --fill --yes
glab mr approve N && glab mr merge N --squash --remove-source-branch --yes

GitLab Approval / CODEOWNERS / Push Rules (Premium+)

glab api -X POST "projects/P/approval_rules" -f name=Default -F approvals_required=2
glab api -X POST "projects/P/approvals" -F merge_requests_author_approval=false -F merge_requests_disable_committers_approval=true
glab api -X PATCH "projects/P/protected_branches/main" -F code_owner_approval_required=true
glab api -X POST "projects/P/push_rule" -f commit_message_regex='^(feat|fix|docs|chore): ' \
  -F prevent_secrets=true -F max_file_size=10 -F deny_delete_tag=true
# CODEOWNERS Location: ./CODEOWNERS → ./docs/CODEOWNERS → ./.gitlab/CODEOWNERS (the first one takes effect)
# [Section] [Section][2] ^[Optional] The last matching entry takes effect

mirror

glab api -X POST "projects/P/remote_mirrors" \
  -f url="https://USER:URLENCODED_PASS@git-codecommit.ca-central-1.amazonaws.com/v1/repos/R" \
  -F enabled=true -F only_protected_branches=true -F keep_divergent_refs=false
glab api "projects/P/remote_mirrors"
glab api -X POST "projects/P/remote_mirrors/MID/sync"
glab api -X DELETE "projects/P/remote_mirrors/MID"
git ls-remote gitlab refs/heads/main; git ls-remote codecommit://cc-dev@R refs/heads/main

Troubleshooting and migration

git config --show-origin --get-all credential.helper
GIT_TRACE=1 GIT_CURL_VERBOSE=1 git ls-remote REMOTE 2>&1 | grep -E "helper|HTTP/"
git config --global credential.https://git-codecommit.REGION.amazonaws.com.helper ''
aws sts get-caller-identity
git clone --mirror SRC repo.git
git push DST 'refs/heads/*:refs/heads/*' 'refs/tags/*:refs/tags/*'
git for-each-ref --format='%(refname):%(refname)' refs/tags | split -l 3000 - tagbatch_
git lfs ls-files; git count-objects -vH

Platform comparison shorthand

demandCodeCommitGitLabGitHub (Lesson 3)Azure Repos (Lesson 3)
Direct push to main is prohibitedIAM Deny + References + NullProtected branch push=No onerulesetbranching strategy
Approval requiredApproval rule templateApproval Rules (Premium)Number of rule set approvalsMinimum reviewers
path owner—CODEOWNERS(Premium)CODEOWNERSAutomatically include reviewers
Commit Specifications/Prohibition of Confidential Documents— (Self-built inspection required)Push rules (Premium)Rule Set Metadata Rules/Push Protection—
Human certification recommendedGRC + Identity CenterOAuth(GCM/glab)/ PATGCMGCM + Entra ID
LFSNot supported (as of 2026-11-15)supportsupportsupport

Comprehensive experiment: dual-platform protection + GitLab → CodeCommit push image

About 30 minutes · Connect M2–M8: build repositorys on each platform and protect main, use GitLab as the only writing source to mirror to CodeCommit, and clean up after verification
After classEstimated cost $0 (within free tier)
sceneYour team decides: GitLab.com is the master repository (MR + protected branch), and the build machines in the AWS isolated network pull code from the CodeCommit read-only mirror. Requirements: ① No one can directly push main on both platforms; ② GitLab changes appear in CodeCommit within 1 minute; ③ CodeCommit mirrors are only readable by humans, only mirror robots can write; ④ There are no long-term AWS access keys in the entire process (except for the Git credentials of mirror robots); ⑤ All resources and credentials are cleared after the experiment.
ResourcescostRequired permissionsCleaning method
CodeCommit repositorymyapp、myapp-mirrorFree tier (≤ 5 active users)cc-dev(PowerUser)、cc-admin(IAM)aws codecommit delete-repository
IAM: DenyChangesToMain, deny-mirror-writes, gitlab-mirror-bot + Git credentials, approval rule templatesfreeIAM administratorDelete Credentials → Delete Inline Policy → Delete User → Detach and Delete Policy → Delete Template
GitLab projectsalice-git-lab/myapp, mirror, PATFreeGroup OwnerDelete image → Delete project → Undo PAT
(Optional) CodeConnections connection, SNS topicFree / Free Tiercc-admindelete-connection、sns delete-topic
Prepare identities and tools:aws sso login --profile cc-dev(Developer) with--profile cc-admin(Administrator);glab auth status;Confirm~/git-lab/myappclean (git status)。
export AWS_REGION=ca-central-1
ACCOUNT=$(aws sts get-caller-identity --profile cc-admin --query Account --output text)
GL_NS=alice-git-lab; P="${GL_NS}%2Fmyapp"
CodeCommit main repository myapp: push and protect main (M2, M3)
cd ~/git-lab/myapp
aws codecommit get-repository --repository-name myapp --profile cc-dev >/dev/null 2>&1 || \
  aws codecommit create-repository --repository-name myapp --profile cc-dev
git remote get-url cc 2>/dev/null || git remote add cc codecommit::ca-central-1://cc-dev@myapp
git push cc --all && git push cc --tags
# Administrator: Create and mount DenyChangesToMain (M3 command paging), associate 2-approver-rule-for-main template
git commit --allow-empty -m "test: direct push" && git push cc main; git reset --hard HEAD~1

Expectation: The last push returns 403.

GitLab project: push and protect main (M5), optionally configure approval/CODEOWNERS/push rules (M6)
glab repo view "$GL_NS/myapp" >/dev/null 2>&1 || glab repo create "$GL_NS/myapp" --private --defaultBranch main
git remote get-url gitlab 2>/dev/null || git remote add gitlab "https://gitlab.com/$GL_NS/myapp.git"
git push gitlab --all && git push gitlab --tags
glab api -X DELETE "projects/$P/protected_branches/main" || true
glab api -X POST "projects/$P/protected_branches" -f name=main -f push_access_level=0 -f merge_access_level=30
git commit --allow-empty -m "test: direct push" && git push gitlab main; git reset --hard HEAD~1

Expectations:remote: GitLab: You are not allowed to push code to protected branches on this project.

CodeCommit mirror repository and robot (M7):Createmyapp-mirror;Confirmgitlab-mirror-botThe inline policy only allows forarn:aws:codecommit:ca-central-1:${ACCOUNT}:myapp-mirrorGitPull/GitPush; generate Git credentials; putdeny-mirror-writesHooked to the developer permission set.
aws codecommit create-repository --repository-name myapp-mirror --profile cc-admin
aws iam get-user-policy --user-name gitlab-mirror-bot --policy-name MirrorPushOnly --profile cc-admin --query PolicyDocument
aws iam list-attached-user-policies --user-name gitlab-mirror-bot --profile cc-admin # Should not have DenyChangesToMain
Create a push image in GitLab(M7 command page "Create Mirror", check only mirror protected branches), synchronize and check immediately:
MID=$(glab api "projects/$P/remote_mirrors" | python3 -c 'import sys,json;print(json.load(sys.stdin)[0]["id"])')
glab api -X POST "projects/$P/remote_mirrors/$MID/sync"; sleep 45
[ "$(git ls-remote gitlab refs/heads/main | cut -f1)" = "$(git ls-remote codecommit::ca-central-1://cc-dev@myapp-mirror refs/heads/main | cut -f1)" ] && echo "MIRROR OK"
End-to-end verification: Merge a change into GitLab main through MR, the mirror will advance after a timeout of ≤ 1 minute; directly push the mirror as a developer → 403; on the mirrorgit cloneSuccessful (read-only available).
git switch -c docs/final-lab && echo "final lab $(date -u +%F)" >> docs/adr/0004-hosting.md
git commit -am "docs: final lab check" && git push -u gitlab docs/final-lab -o merge_request.create -o merge_request.target=main
glab mr merge --squash --remove-source-branch --yes
sleep 60; git ls-remote codecommit::ca-central-1://cc-dev@myapp-mirror refs/heads/main
git push codecommit::ca-central-1://cc-dev@myapp-mirror HEAD:refs/heads/hack # Expect 403
(optional)CodeConnections:Create a GitLab connection and complete the handshake (M4), confirmAVAILABLEDelete later.
Clean up (must be done)
# GitLab: Delete image and project, revoke PAT (User Settings → Access Token)
glab api -X DELETE "projects/$P/remote_mirrors/$MID"
glab repo delete "$GL_NS/myapp" --yes # GitLab.com may enter the "pending deletion" state first, and then delete it completely according to the retention period
# AWS: repository
for r in myapp myapp-mirror; do aws codecommit delete-repository --repository-name $r --profile cc-admin; done
# Approval rule template (disassociate first, you can delete it directly if the repository has been deleted)
aws codecommit delete-approval-rule-template --approval-rule-template-name 2-approver-rule-for-main --profile cc-admin
# Mirrorbot: Credentials → Inline Policy → User
for id in $(aws iam list-service-specific-credentials --user-name gitlab-mirror-bot --profile cc-admin \
            --query 'ServiceSpecificCredentials[].ServiceSpecificCredentialId' --output text); do
  aws iam delete-service-specific-credential --user-name gitlab-mirror-bot --service-specific-credential-id $id --profile cc-admin; done
aws iam delete-user-policy --user-name gitlab-mirror-bot --policy-name MirrorPushOnly --profile cc-admin
aws iam delete-user --user-name gitlab-mirror-bot --profile cc-admin
#Customer hosting strategy: first separate from role/permission set, then delete
aws iam list-entities-for-policy --policy-arn arn:aws:iam::${ACCOUNT}:policy/DenyChangesToMain --profile cc-admin
# … detach-role-policy / detach-customer-managed-policy-reference-from-permission-set …
aws iam delete-policy --policy-arn arn:aws:iam::${ACCOUNT}:policy/DenyChangesToMain --profile cc-admin
# Local: remove remote
git remote remove cc; git remote remove gitlab
aws sso logout

If you have created SSH public keys, SNS topics, notification rules, triggers, and CodeConnections connections, they are also deleted; GitLab revokes the OAuth authorization for the AWS connection.

Acceptance Checklist

Open-ended self-assessment (answer yourself first, then expand for reference answers)

1.Why can't Identity Center users use CodeCommit's HTTPS Git credentials? How should they be connected?

Git credentials are service-specific credentials for IAM users. Identity Center users are just sessions that assume roles in IAM and do not have IAM user objects. AWS CLI v2 should be installed with git-remote-codecommit, using SSO configuration files andcodecommit::area://config file@repositoryFor URL connections, GRC calculates SigV4 signatures using session temporary credentials.

2.CodeCommit branch protection strategyNullWhat is the role of conditionals? What will happen if it is removed?

"Null": {"codecommit:References": "false"}The References context key is required to exist in the request for Deny to take effect. After removingStringEqualsIfExistsTrue when the key does not exist. Requests without the key during push will also be rejected, causing the push of any branch to fail. It is officially required that all Deny strategies containing GitPush add Null conditions.

3.Can the CodeCommit approval rule template prevent direct push to main? What is the complete solution?

No, it only constrains PR merges. Complete solution: IAM Deny (GitPush, PutFile, DeleteFile, DeleteBranch, Merge*) + References/Null conditions are attached to the developer, the approval rule template constrains the PR, the release person in charge/assembly line role retains merge permissions, and the approval rule coverage event alerts.

4.Describes GitLab's internal process for rejecting pushes to protected branches.

Gitaly receives the push (receive-pack), runs the pre-receive hook before updating the ref, and calls the Rails internal API/internal/allowed;Rails checks project permissions, protected branches, push rules, etc., and returns false and a message if failed; the hook exits with non-zero, ref is not updated; the client displaysremote: GitLab: … with pre-receive hook declined。

5.Who are the UseConnection and PassConnection of CodeConnections given to? Why is the connection PENDING?

UseConnection is for the service role that uses connections during runtime (such as the CodePipeline service role), and you can add conditions such as FullRepositoryId; PassConnection is for the operator who creates/updates the pipeline and hands the connection ARN to the service (PassedToService condition). Connections created by CLI/CloudFormation are PENDING by default and must complete the OAuth handshake with the provider in the console before they become AVAILABLE.

6.GitLab → CodeCommit What are the common failures in pushing images? How to monitor?

Git credentials are deactivated/rotated, passwords are not URL-encoded, IAM policy changes (the mirror robot is Deny), the mirror target is directly modified by someone, resulting in a fork (Keep divergent refs fails, and is overwritten by default), more than 4000 references, contains LFS objects (not supported by CodeCommit). Monitoring: Regularly check with APIupdate_status/last_successful_update_at, CodeCommit notification rules do heartbeats, and the runbook is rotated according to credentials.

Final exam (12 questions, covering all modules)

Sources and imprints

Verification basis for all technical facts in this lesson (verification date: 2026-11-15)
TopicVerify conclusionSource (Accessed on 2026-11-15)
CodeCommit statusNo longer open to new customers on 2024-07-25; GA resumption announced on 2025-11-24 (documentation history 2025-11-25); 29 regions; unchanged pricing with 99.9% SLA; roadmap: Git LFS 2026 Q1, eu-south-2/ca-west-1 starting in 2026 Q3. As of the verification date, there are no LFS and new region online records on the document history and quota pages.AWS DevOps Blog (2025-11-24) · Document history · Quota
CodeCommit connection methodGit credentials are the "easiest way"; federated access/temporary credentials/web identities cannot use Git credentials, git-remote-codecommit is recommended; GRC can also be used for IAM users without Git credentials; AWS CLI v2 is required to support SSO and temporary credentials; SSH and CLI Credential Assistants are alternatives, which may conflict with system assistants; URL formatcodecommit://profile@repo、codecommit::region://repoSetting up · git-remote-codecommit
branch restriction strategyDeny action list (GitPush, DeleteBranch, DeleteFile, PutFile, MergeBranchesBy*×3, MergePullRequestBy*×3);StringEqualsIfExists codecommit:References + Null … "false", Null is required for the Deny policy containing GitPush; it is recommended to attach it to a group or roleLimit pushes and merges to branches
Approval rule templateContent Version 2018-11-08, DestinationReferences, Approvers/NumberOfApprovalsNeeded/ApprovalPoolMembers; wildcard characters are required for role assignment sessions; cross-account approval is not supported; quota: template 1000/region, rules on PR ≤ 30 (template ≤ 25), pool members ≤ 50, content ≤ 3000 charactersCreate an approval rule template· Quota page
Notifications and triggersNotification event IDs (comments, approvals-status-changed / rule-override, pull-request-created / source-updated / status-changed / merged, branches-and-tags-created / deleted / updated); trigger events all / updateReference / createReference / deleteReference; not supported by SNS FIFO; ≤ 10 triggers per repositoryNotification concepts · Trigger for SNS
CodeCommit quotablob ≤ 2 GB; console/API/CLI single file ≤ 6 MB; single push ≤ 4000 references; repository ≤ 5000/account (adjustable); ca-central-1 is in the region listQuota page
CodeCommit PricingThe free tier is valid for new and old customers for a long time; an example of 6 active users is $1; excess storage is $0.06/GB-month, and requests are $0.001/time; active user definitions include identities created by the service. The pricing page did not list free quota values at that time. The 50 GB / 10,000 times / 10 GB and 2,000 times per paid user in this lesson are the long-term public quotas of AWS, and are marked as "Subject to the pricing page"CodeCommit pricing
CodeConnectionsProvider: Bitbucket, GitHub/GHEC, GHES, GitLab, GitLab self-managed, Azure DevOps; console use starting from 2024-07-01codeconnectionsARN, the old prefix is still available, and the policy prefix must match the resource; CLI/CloudFormation is created as PENDING and needs to be updated by the console; GitLab connection requires the Owner role and only provides access to authorized accounts; UseConnection / PassConnection and condition keysCreate a connection to GitLab · IAM reference
GitLab version19.5 released on 2026-10-15; released monthlyGitLab 19.5 release notes
GitLab protected branchesAll plans; options No one / Developers + Maintainers / Maintainers (+ Deployment Key); per user/group authorization, group-level protected branches, code owner approval for Premium/Ultimate; default branch automatically protected; most lenient when multiple rules take effect; "Require code owner approval" while denying direct pushProtected branches
GitLab Approval / CODEOWNERS / Push RulesThe approval rules page is Premium/Ultimate; the creator is prohibited from approving by default, and the committer can approve by default; CODEOWNERS (Premium/Ultimate) is based on the root directory → docs/ → .gitlab/ Find the first one; push rules (Premium/Ultimate) include commit message/branch name/author email regularity, reject unsigned, prohibit tag deletion, prohibit confidential files (files_denylist.yml, by file name), file name regularity, maximum file size, DCOApproval rules · Code Owners · Push rules
GitLab push imageAll plans; synchronize within 5 minutes after push, within 1 minute when only mirroring protected branches; fork refs are overwritten by default, marking fails when Keep divergent refs and can only be modified with API; CodeCommit configuration steps (IAM user, ARN of explicit region and account, Git credentials, it is recommended to only mirror protected branches)Push mirroring

Video verification instructions

The title and channel of the following video were verified through the YouTube oEmbed interface on 2026-11-15: Valentin Despa "Git for GitLab (Beginner's FULL COURSE)" (4lxvVj7wlZw); TechWorld with Nana "GitLab CI CD Tutorial for Beginners [Crash Course]" (qP8kir2GUgo); Programming with Mosh "Git Tutorial for Beginners: Learn Git in 1 Hour" (8JJ101D3knE); freeCodeCamp.org "Git and GitHub for Beginners - Crash Course" (RGOj5yH7evk). oEmbed does not return the duration and release date, so the duration is not written in the card. Verified feature videos for AWS CodeCommit (git-remote-codecommit, approval rules, after GA is restored in 2025), CodeConnections, GitLab CODEOWNERS/push rules, and GitLab→CodeCommit mirrors were not found. Storyboards are provided for the corresponding modules. All videos are in English and the interface may differ from the current version.

Audio explanation

The Speech tab uses the browser's Web Speech API (speechSynthesis, zh-CN) read the explanation text aloud in real time. English terms are pronounced in en-US. The effect depends on the voice installed in the operating system. This courseware does not have MP3 embedded; when offline audio is needed, the transcript can be generated by the TTS service.

Known limitations

  • The experimental commands are not actually executed in the production environment of this courseware; the account ID, ARN, SHA, credential ID, time and version number in "Expected Output" are all sample values.
  • CodeCommit Git LFS and new regions: It is only judged as "not yet online" based on the user guide document history and quota page as of 2026-11-15. If AWS releases it later, please refer to What's New.
  • The specific value of CodeCommit's free quota (50 GB, 10,000 times, 10 GB / 2,000 times per paying user) is not shown in the text of the pricing page on the day of verification, and is marked as "subject to the pricing page" in the courseware; the cost calculator is for estimation only.
  • The signing details of git-remote-codecommit (username/password format, specification request) are organized according to its open source implementation, and are implementation details and may change.
  • The original text of the rejection message of GitLab push rules, confidential file interception, etc. changes with the version, and is marked as an example in the courseware; the two rejection messages of the protected branch are the long-term stable original text.
  • The package attribution of GitLab functions may be adjusted (for example, the functions are devolved to Free), which shall be subject to the Tier mark at the top of each document page; the number of members, storage and other quotas of GitLab.com Free shall be subject to the current policies of GitLab.com.
  • The timing, signature value, and timing in the animation are schematic and are used to illustrate the mechanism.