Git Hour 4: Towards a Hosted Platform (AWS CodeCommit and GitLab)
- 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, understand
PENDING → 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
| # | time | module | core content | animation/interaction | experiment |
|---|---|---|---|---|---|
| 0 | before class | Warm-up and platform account preparation | AWS account and IAM Identity Center, GitLab.com account, AWS CLI v2, git-remote-codecommit, glab; reuse the myapp practice repository | Environmental self-check list | aws sts get-caller-identity、glab auth status |
| 1 | 00–05 | Git service positioning between AWS and GitLab | CodeCommit will stop updating in 2024, resume GA and roadmap in 2025-11; GitLab SaaS / Dedicated / self-managed; package differences | CodeCommit Timeline + Platform Selector | Check available areas and account status |
| 2 | 05–13 | CodeCommit: Authentication with git-remote-codecommit | Four connection methods and recommended order, IAM Identity Center configuration file, Git credentials, SSH,aws codecommit CLI | Core Animation: GRC uses temporary credentials for SigV4 signing | Clone and push myapp with SSO configuration file |
| 3 | 13–21 | CodeCommit: branch protection, approval rules and notifications | IAM Deny + codecommit:References + Null;Approval rule template;Notification rule;Trigger | IAM policy evaluator | Refuse to push main + 2 people approve PR |
| 4 | 21–28 | CodeConnections: Connecting GitHub/GitLab to AWS | Supported providers, PENDING handshake, host resources,UseConnection/PassConnection, condition key | connection state machine | Create a GitLab connection and complete the handshake |
| 5 | 28–37 | GitLab: Projects, Protected Branches, and MR | Groups/projects/roles, protected branch options, MR merge methods,glab CLI | Core Animation: Protected branch rejects push | Protect main and merge with MR |
| 6 | 37–44 | GitLab: Approval Rules, CODEOWNERS, and Push Rules | Approval rules and settings, CODEOWNERS location and syntax, push rules and packages | MR Approval Calculator | CODEOWNERS + Push Rules (Premium Trial) |
| 7 | 44–54 | Cross-platform mirroring and troubleshooting practice | Push/Pull Mirrors, CodeCommit 403, Credential Assistant Violation, Protected Branch Rejection, Large Files and LFS | Mirror Sync Simulator + Interactive Troubleshooting Tree | GitLab → CodeCommit push image |
| 8 | 54–60 | Migration, costs and self-testing | GitHub/Azure Repos ↔ GitLab/CodeCommit migration, CodeCommit billing, GitLab package, self-test | cost calculator | git push --mirrorMigrate in batches |
| — | After class | cheat sheet · Comprehensive experiment | CodeCommit and GitLab dual platform protection + push image + verification + cleaning | Final exam 12 questions | Comprehensive experiment |
Knowledge Coverage Matrix Knowledge Coverage Matrix
| target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | key commands | experiment |
|---|---|---|---|---|---|---|---|---|---|---|
| Choose hosting platform and deployment form | ✓ | · | · | ✓ | · | · | · | ✓ | aws codecommit list-repositories | M1 |
| CodeCommit Authentication (GRC / Git Credentials / SSH) | · | ✓ | · | · | · | · | ✓ | · | git clone codecommit::REGION://PROFILE@REPO | M2 |
| CodeCommit branch protection and approval | · | · | ✓ | · | · | · | ✓ | · | create-approval-rule-template | M3 / Comprehensive Experiment |
| Notifications, triggers and events | · | · | ✓ | · | · | · | · | · | put-repository-triggers | M3 |
| External repository access to AWS (CodeConnections) | · | · | · | ✓ | · | · | · | ✓ | aws codeconnections create-connection | M4 |
| GitLab protected branches and MR | · | · | · | · | ✓ | ✓ | ✓ | · | glab mr create、glab api protected_branches | M5 / Comprehensive Experiment |
| Approval rules, CODEOWNERS, push rules | · | · | ✓ | · | · | ✓ | · | · | glab api push_rule | M6 |
| Cross-platform mirroring | · | · | · | · | · | · | ✓ | ✓ | glab api remote_mirrors | M7 / Comprehensive Experiment |
| Platform troubleshooting (403, credential conflict, push rejection, large files) | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | · | GIT_TRACE=1、GIT_CURL_VERBOSE=1 | M7 Troubleshooting Tree |
| Migration and Cost Assessment | ✓ | · | · | · | · | · | · | ✓ | git push --mirror | M8 |
What’s excluded from this lesson (and where to learn it)
| Topic | Why not in this lesson | where to study |
|---|---|---|
| Azure Repos, GitHub (rule sets, GCM, merge queue) | Belongs to the previous lesson | Lesson 3 |
CodePipeline / CodeBuild pipeline, GitLab CI/CD (.gitlab-ci.yml) details | This 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 architecture | Belongs to the topic of architecture | Lesson 6 |
History rewritten (git filter-repo), remove leaked secrets | In-depth debugging | Lesson 7 (This lesson only explains how to block on the platform side) |
| GitLab Runner, security scanning (SAST/DAST), GitLab Duo | Beyond Git hosting itself | docs.gitlab.com |
How to use this courseware
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.
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).
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.
Module 0 · Warm-up and platform account preparation (completed before class)
- 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 area
ca-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)
| Project | Dosage for this lesson | cost | Required permissions |
|---|---|---|---|
| CodeCommit | 2–3 test repositories, 1–2 active identities | The 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$0 | AWSCodeCommitPowerUser(Exercise) + Create an IAM Policy (Admin) |
| IAM / IAM Identity Center | 1 permission set or role, 1 image-specific IAM user | free | IAM administrator or Identity Center administrator |
| CodeConnections | 1 connection | The 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 topic | Within free tier | sns:CreateTopicWait |
| GitLab.com | 1 group, 1–2 projects | Free; Premium features require trial or payment | Group Owner/Project Maintainer |
FAKE_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
origin/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).
Module 1 · Git service positioning of AWS and GitLab
- 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").
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
| Date | event | what does it mean to you |
|---|---|---|
| 2015-07-09 | CodeCommit User Guide first released | — |
| 2020-03-04 | Introducing git-remote-codecommit as the recommended method for federated/temporary credential access | The heart of the M2 |
| 2023-12-21 | Support for customer managed KMS keys | Self-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 blog | A large number of teams are beginning to move out to GitHub/GitLab |
| 2025-11-24 | AWS 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 migration | CodeCommit becomes optional again during selection |
| 2025-11-25 | User 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. |
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 Dedicated | GitLab Self-Managed | |
|---|---|---|---|
| Who operates and maintains | GitLab | GitLab (single tenant, hosted on AWS) | Yourself (Omnibus, Helm, Operator) |
| Version | Continuous deployment, always up to date | GitLab management upgrade window | You decide when to upgrade (released monthly, third Thursday) |
| Package | Free / Premium / Ultimate | Ultimate | CE (Free Open Source) or EE (Free/Premium/Ultimate License) |
| Administrator settings | No instance administrator; group Owner is the highest | Partially configurable | Full control (Admin area, such as default branch protection, file size limit) |
| suitable for | most teams | High data residency/isolation requirements | Intranet, offline, in-depth customization |
The functions and packages used in this lesson (subject to the Tier annotation on the docs.gitlab.com page)
| Function | Free | Premium | Ultimate |
|---|---|---|---|
| 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
| scene | Recommended | Reason |
|---|---|---|
| All workloads are in AWS, identities are unified in IAM Identity Center, and the code is required not to leave the AWS account/region | CodeCommit | No additional identity system; VPC interface endpoints; CloudTrail auditing; KMS |
| Requires Issue, MR, CI, and product library integration, multi-cloud | GitLab | Platform 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 code | Main repository + CodeCommit read-only mirror | M7 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 |
Architecture diagram: Identity and repository models for both platforms
Timeline: CodeCommit status changes
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.
platform selector
Core command: Confirm platform status
| command | function | Description |
|---|---|---|
aws codecommit list-repositories | List repositorys in the current region | Being able to return (even if it is an empty list) indicates that the account can use CodeCommit |
aws codecommit create-repository | Create repository | New 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/regions | Query service available areas | AWS public parameters, the results are subject to the actual return |
glab api version | Query GitLab instance version | Self-Managed Check before and after upgrade |
glab api namespaces/:id/Group settings page | View group packages | Packages 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)
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
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".
docs/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.
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"])'
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
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
- AWS CodeCommit returns to General Availability(2025-11-24)
- CodeCommit User Guide Documentation History
- CodeCommit quota
- GitLab: Choose a subscription
Video storyboard (approximately 60 seconds)
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.
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.
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.
Module 2 · CodeCommit: Authentication and git-remote-codecommit
- 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.
What: Four connection methods
| way | Clone URL | Identity type | Credential form | AWS Documentation Location |
|---|---|---|---|---|
| git-remote-codecommit(GRC) | codecommit::ca-central-1://cc-dev@myapp | IAM Identity Center, federated identities, roles, root accounts, IAM users | Use AWS credentials for each connectionCurrent calculation SigV4 signature | Federated/Temporary Credentials AccessRecommendedway; also available for IAM users without generating Git credentials |
| HTTPS + Git credentials | https://git-codecommit.ca-central-1.amazonaws.com/v1/repos/myapp | IAM users only | IAM generatedstaticUsername/password (max 2 sets per user) | "The easiest way to set up CodeCommit", compatible with IDEs and third-party tools |
| SSH | ssh://git-codecommit.ca-central-1.amazonaws.com/v1/repos/myapp | IAM users only | Upload 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 Assistant | Same as HTTPS | IAM users, EC2 instance roles, etc. | aws codecommit credential-helpercash signature | Alternative; prone to conflict with System Credential Assistant (M7) |
codecommit://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
- remote helper dispatch: Git sees URL scheme
codecommit(formed likecodecommit::REGION://PROFILE@REPOorcodecommit://PROFILE@REPO), executed in PATHgit-remote-codecommit <remote> <url>(withgit-remote-httpssame mechanism). - Parse URL: Get the area (the default is to get the area of the configuration file), the configuration file name (the default
default), repository name. - Get credentials: Resolve credential chain by profile via botocore - SSO cache (
~/.aws/sso/cache)、role_arnSubstitute, environment variables, etc., and getAccessKeyId / SecretAccessKey / SessionToken。 - SigV4 signature:Request for specification (method
GIT, path/v1/repos/myapp, host header) with service namecodecommit, region, current UTC time to derive the signing key and compute the HMAC-SHA256 signature. - 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。 - Leave it to Git HTTPS transport: call
git 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
| scene | Choose |
|---|---|
| Developer Notebook, Corporate Identity Center | GRC + 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 internals | Using 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
| CodeCommit | GitHub | Azure Repos | GitLab | |
|---|---|---|---|---|
| Recommended Human Authentication | GRC + Identity Center | GCM (OAuth Browser Flow) | GCM + Entra ID | GCM/glab (OAuth) or PAT |
| static credentials | Git credentials (IAM user) | Fine-grained PAT | PAT | PAT/Project Access Token/Deployment Token |
| SSH | RSA public key linked to IAM user | Account SSH key/deployment key | SSH public key | User SSH Key/Deployment Key |
Sequence diagram: git push to CodeCommit via git-remote-codecommit
Decision chart: Which approach should I use?
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.
Core commands and parameters
| command | function | Key parameters/description |
|---|---|---|
git clone codecommit::REGION://PROFILE@REPO | GRC clone | Omit the region to use the configuration file region; omitPROFILE@Use default |
git remote add cc codecommit::ca-central-1://cc-dev@myapp | Add CodeCommit remote to existing repository | Remote name is arbitrary |
aws iam create-service-specific-credential | Generate Git credentials for IAM user | --service-name codecommit.amazonaws.com;The password is only displayed once |
aws iam upload-ssh-public-key | Upload SSH public key | ReturnSSHPublicKeyId(APKA…) as SSH username |
aws codecommit create-repository | Create repository | --repository-name --repository-description --kms-key-id --tags |
aws codecommit get-repository | View clone URL, default branch | cloneUrlHttp、cloneUrlSsh、defaultBranch |
aws codecommit list-branches / get-branch | View branches | --repository-name --branch-name |
aws codecommit update-default-branch | Modify default branch | --default-branch-name main |
aws codecommit create-pull-request | Create a PR | --targets repositoryName=,sourceReference=,destinationReference= |
aws codecommit list-pull-requests | List 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)
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"]
}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.
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).
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
aws 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).
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
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:
Official documentation
- Setting up for AWS CodeCommit
- Setup steps for HTTPS connections with git-remote-codecommit
- Connecting with rotating credentials
- aws/git-remote-codecommit (source code)
Video storyboard (approximately 90 seconds)
Screen: terminal input
git 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.
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.
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.
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.
Module 3 · CodeCommit: Branch protection, approval rules and notifications
- 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.
What: CodeCommit’s three-layered “guardrails”
| layer | mechanism | What can be prevented | Can't stop anything |
|---|---|---|---|
| ① IAM condition policy | Deny + codecommit:References | directgit 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/EventBridge | event driven | Does 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 use
StringEqualsIfExists: The condition is "true" when the key does not exist → Deny takes effect →Pushing any branch is rejected。 - plus
Null = 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 rules | repository trigger | EventBridge | |
|---|---|---|---|
| API | AWS CodeStar Notifications(codestar-notifications) | codecommit put-repository-triggers | Default event busaws.codecommit |
| event | Comments, approval status/overrides, PR creation/update/status/merge, branch and tag creation/deletion/update | all、updateReference、createReference、deleteReference | Repository status changes, PR status changes, comments, etc. |
| target | SNS (Standard), Chatbot (Slack/Teams); ≤ 10 goals per rule, ≤ 10 rules per resource | SNS standard topic (FIFO not supported), Lambda; ≤ 10 per repository | Any EventBridge target |
| Purpose | message for people | Simple automation (pushing to call Lambda) | Complex routing, cross-account, startup pipeline |
Compare with GitHub / Azure Repos / GitLab
| Ability | CodeCommit | GitHub | Azure Repos | GitLab |
|---|---|---|---|---|
| It is forbidden to push main directly | IAM Deny + References | Rule set “Require a pull request” | Branch policy (enable to disable direct push) | Protected branch Allowed to push = No one |
| Number of people required for approval | Approval rule template | Number of rule set approvals | Minimum reviewer policy | Approval Rules (Premium) |
| owner by path | None (can only be based on the approver pool) | CODEOWNERS | Automatically include reviewers (path filtering) | CODEOWNERS(Premium) |
| Build verification | Requires EventBridge + CodeBuild to write back PR approval/comment by yourself | Required status check | Build a validation strategy | "The assembly line must succeed" |
git 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?
Structure diagram: Approval rule template JSON
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.
Core commands and parameters
| command | function | Description |
|---|---|---|
aws iam create-policy / attach-role-policy / attach-group-policy | Create and mount a branch protection policy | In Identity Center, the policy is an inline/customer-managed policy for a permission set. |
aws codecommit create-approval-rule-template | Create template | --approval-rule-template-contentJSON string |
aws codecommit associate-approval-rule-template-with-repository | associated to repository | For batch usebatch-associate-… |
aws codecommit get-pull-request-approval-states | View approval status | need --revision-id |
aws codecommit update-pull-request-approval-state | Approve/Withdraw Approval | --approval-state APPROVE|REVOKE |
aws codecommit evaluate-pull-request-approval-rules | Determine whether the rules are met | Returnapproved、overridden |
aws codecommit override-pull-request-approval-rules | Override rules (should be restricted and alert) | --override-status OVERRIDE |
aws codecommit merge-pull-request-by-squash | Merge PR | There is also fast-forward / three-way |
aws codecommit put-repository-triggers / test-repository-triggers | trigger | events:all / updateReference / createReference / deleteReference |
aws codestar-notifications create-notification-rule | notification 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)
cc-devPermission set/role used (see Commands tab), wait approximately 1 minute for IAM changes to propagate.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。
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.
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.
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
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
- Limit pushes and merges to branches
- Working with approval rule templates
- Manage triggers for a repository
- Notification concepts (list of event IDs)
Video storyboard (approx. 75 seconds)
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.
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.
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.
Module 4 · CodeConnections: Connecting GitHub/GitLab repositories to AWS
- 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 status
PENDING → 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.
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.
| provider | Need host resources? | Remarks |
|---|---|---|
| GitHub / GitHub Enterprise Cloud | No | Install the AWS Connector for GitHub App |
| GitHub Enterprise Server | Yes | Can be placed within a VPC (codeconnections:VpcIdcondition key) |
| GitLab.com | No | OAuth authorization; the creator needs to haveOwnerRole (repositories in a group do not require group Owner) |
| GitLab Self-Managed | Yes | Requires personal access token (api scope) to register host |
| Bitbucket Cloud | No | Install app |
| Azure DevOps | No | Newer 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.
How: life cycle
CreateConnection(Console, CLI, CloudFormation) → StatusPENDING。- "Update pending connections" in the console: Jump to provider login → Authorize/Install application → Return → Status
AVAILABLE. This step requires handshake class permissions:StartOAuthHandshake、GetInstallationUrl、ListInstallationTargets、UpdateConnectionInstallation、GetIndividualAccessToken(These are "IAM permissions only", not API actions). - When creating/updating a pipeline, the operator needs to
PassConnection(condition keycodeconnections:PassedToService, such ascodepipeline.amazonaws.com)。 - When the pipeline is running,service roleneed
UseConnection(availableFullRepositoryId、BranchName、ProviderPermissionsRequired、ProviderActionWait for the condition key to narrow). - when no longer in use
DeleteConnection, and uninstall the application/revoke OAuth authorization on the provider side.
When: Connection vs Mirroring
| demand | CodeConnections | Push the image to CodeCommit (M7) |
|---|---|---|
| CodePipeline builds from GitHub/GitLab | ✓ First choice | Yes, 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 | ✓ | ✗ |
PENDING, 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
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.
Core commands and parameters
| command | function | Description |
|---|---|---|
aws codeconnections create-connection | Create connection | --provider-type GitHub|GitLab|Bitbucket|GitHubEnterpriseServer|GitLabSelfManaged|AzureDevOps、--connection-name, self-management time--host-arn |
aws codeconnections get-connection | View status | ConnectionStatus:PENDING / AVAILABLE / ERROR |
aws codeconnections list-connections | list connections | --provider-type-filter |
aws codeconnections create-host | Create a host for self-managed GitLab/GHES | --provider-endpoint https://gitlab.example.com, optional--vpc-configuration |
aws codeconnections delete-connection | Delete connection | Remember to revoke authorization on the provider side |
aws codestar-connections … | old prefix command | Still 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)
glab repo create alice-git-lab/myapp --private)。PENDING。gitlab-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
aws 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.
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
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
- What are connections?
- Create a connection to GitLab
- Update a pending connection
- CodeConnections Permissions Reference
Video storyboard (approximately 60 seconds)
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.
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.
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.
Module 5 · GitLab: Projects, Protected Branches, and Merge Requests
- 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.
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.
| role | Typical permissions associated with repositories |
|---|---|
| Guest | Code cannot be read in private projects (you can view Issues, etc.) |
| Planner | Planning functions (Issue, Epic), not code-oriented (new in GitLab 17.7) |
| Reporter | Read code, clone, pull; cannot push |
| Developer | push toNot protectedBranch, create MR; protected branches depend on rules |
| Maintainer | Manage protected branches, push rules, images, members (excluding Owner) |
| Owner | Highest 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
| Options | Optional value | meaning |
|---|---|---|
| Branch | name or wildcard likemain、release/*、*-stable | Case sensitive; when multiple rules match the same branchThe most lenient takes effect |
| Allowed to merge | No 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 merge | No one / Developers + Maintainers / Maintainers / Deployment key (Premium can add users/groups) | who canDirect git push(Can also be merged) |
| Allowed to force push | on/off | After it is turned on, anyone with push permission can force push |
| Require approval from code owners | On/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
- client
git pushReached via HTTPS (Workhorse) or SSH (gitlab-shell)Gitaly, the latter runsgit receive-packReceive object. - Executed before updating refpre-receiveHook, Gitaly carries "old SHA, new SHA, ref name, user, protocol" to call GitLab Rails' internal API
POST /api/v4/internal/allowed。 - 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.
- Any check fails → return
status: falseWith messages, Gitaly lets pre-receive exit non-zero, refNot updated(The object may have been uploaded but discarded). - Client printing
remote: GitLab: …with! [remote rejected] main -> main (pre-receive hook declined)。
Key settings for Merge Request
| Settings (Project → Settings → Merge Requests) | Options |
|---|---|
| Merge method | Merge commit / Merge commit with semi-linear history / Fast-forward merge |
| Squeeze commits (squash) | Do not allow / Allow / Encourage / Require |
| merge check | Pipeline must be successful, all discussions must be resolved, (Premium) requires approval |
| Delete source branch by default | on/off |
When: Common configuration templates
| branch | Allowed to merge | Allowed to push and merge | Force push |
|---|---|---|---|
main | Developers + Maintainers (with approval) or Maintainers | No one | close |
release/* | Maintainers | No one | close |
env/production(Pushed by CI) | No one | Deployment key/bot | close |
Compare to Lesson 3
| GitLab protected branches | GitHub ruleset | Azure Repos branching strategy | CodeCommit | |
|---|---|---|---|---|
| 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) |
| bypass | Roles/users in Allowed to push and merge | Bypass list | "Bypass policy" permissions | Deny’s identity is not listed |
*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
Structure diagram: Rule matching and "most relaxed effect"
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.
Core commands and parameters
| command | function | Key parameters |
|---|---|---|
glab repo create | Create project | GROUP/NAME --private --defaultBranch main --description |
glab mr create | Create MR | --source-branch --target-branch main --title --description --fill --squash-before-merge --remove-source-branch |
glab mr list / view / diff | View MR | --state opened |
glab mr approve / revoke | Approve / Withdraw | MR number |
glab mr merge | merge | --squash --remove-source-branch --auto-merge(Automatically merged after pipeline success) |
glab api | Call 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.create | Create 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)
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'
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.
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
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.
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
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
Official documentation
Video storyboard (approx. 75 seconds)
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.
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.
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.
Module 6 · GitLab: Approval Rules, CODEOWNERS and Push Rules
- 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.
What: The action points of the three mechanisms
| mechanism | Timing of action | Package | failure performance |
|---|---|---|---|
| Approval rules | MR merge | Premium/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 |
| CODEOWNERS | When MR is merged ("code owner" approval rules are automatically generated); direct push is also refused after "requires code owner approval" is turned on | Premium / Ultimate | Pending approvals listed in MR for each segment owner |
| Push rules | When git push (pre-receive, the same link of M5) | Premium / Ultimate | remote: GitLab: … + pre-receive hook declined |
| Confidential push protection | Scan key pattern by content when git push | Ultimate | Push 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)
| Category | rules | Example |
|---|---|---|
| User verification | Reject unverified users, reject inconsistent user names, check whether the author is a GitLab user, and author email regularity | @example\.com$ |
| Commit message | Must match / must not match regular | ^(feat|fix|docs|chore|refactor|test)(\(.+\))?: .+ |
| branch name | Branch name regularity | ^(main|release/.+|(feature|fix|docs)/[a-z0-9._-]+)$ |
| Prevent misuse | Reject unsigned commits and prohibit using git push to delete tags | — |
| File | Disable pushing confidential files, Prohibited file name regularization, maximum file size (MB) | (\.tfstate|\.env)$、10 |
| DCO | refuse to lackSigned-off-by:commit | git 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
| target | Configuration |
|---|---|
| main must be reviewed by at least 2 people, and the security directory must be approved by the security team | Approval rule “Default” 2 people + CODEOWNERS[Security] /auth/ @acme/security+ Protected branches enable code owner approval |
| Conventional Commits | Push 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 repository | Ban confidential files + regular file names\.tfstate$+ maximum file size |
Decision diagram: Can MR be merged?
Comparison Chart: Push Rules and Confidential Push 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/ @frankchanged files
Core commands (GitLab REST API, called via glab api)
| endpoint | function | Common fields |
|---|---|---|
POST projects/:id/approval_rules | Create new approval rules | name、approvals_required、user_ids[]、group_ids[]、protected_branch_ids[] |
POST projects/:id/approvals | Approval settings | merge_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_state | Check the status of each MR rule | With code owner rules |
PATCH projects/:id/protected_branches/main | Turn on code owner approval | code_owner_approval_required=true |
POST/PUT projects/:id/push_rule | Create/modify push rules | commit_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)
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
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
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.
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.
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
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
- Merge request approval rules
- Merge request approval settings
- Code Owners · CODEOWNERS syntax
- Push rules
- Secret push protection
Video storyboard (approx. 75 seconds)
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.
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.
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.
Module 7 · Cross-platform mirroring and troubleshooting practice
- 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.
What: Two images of GitLab
| Push image (Push) | Pull the image (Pull) | |
|---|---|---|
| direction | GitLab → External (CodeCommit, GitHub, another GitLab) | External → GitLab |
| Package | Free / Premium / Ultimate | Premium / Ultimate |
| trigger | When 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 on | Scheduled polling (can be triggered by API) |
| Certification | Username + password (token) or SSH public key | Tongzuo |
| Fork processing | DefaultCoverForked 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)
- 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。
- generated for this userHTTPS Git credentials(Not the IAM user ID, not the access key).
- GitLab Project → Settings → Repository → Mirror Repository: Fill in the URL
https://git-codecommit.<Zone>.amazonaws.com/v1/repos/<Repository>, direction Push, authentication method "username and password", fill in Git credentials. - GitLab recommends leaving CodeCommit checked"Mirror only protected branches” (push more frequently, faster).
- 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.
Platform difference quick check (most commonly used when troubleshooting)
| Project | CodeCommit | GitLab.com |
|---|---|---|
| Git LFS | Not supported(2026 Q1 roadmap project, as of 2026-11-15, the document has not been online) | Supported (all plans) |
| single object/file | Single blob ≤ 2 GB; console/API/CLI single file ≤ 6 MB | Maximum 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 feedback | HTTP 403, no reason text | remote: GitLab: …specific reasons |
| Authentication failed | 403 (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):
- 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. - 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 execution
credential rejectIt may recover later, or it may fail repeatedly. - Fix: Configuring a CodeCommit host with URL scopeClearlist of helpers (null
helper =), 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).
Architecture diagram: GitLab main repository + CodeCommit read-only mirror
Flowchart: "Intermittent 403" due to Credential Assistant conflict
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".
Core commands
| command | function | Description |
|---|---|---|
glab api -X POST projects/:id/remote_mirrors | Create a push image | url(Credentials can be embedded, URL encoding is required),enabled、only_protected_branches、keep_divergent_refs |
glab api projects/:id/remote_mirrors | Check image status | update_status、last_successful_update_at、last_error |
glab api -X POST projects/:id/remote_mirrors/:mid/sync | Force immediate sync | limited by frequency |
glab api -X PUT projects/:id/remote_mirrors/:mid | Modification (including keep_divergent_refs) | Keep divergent refs can only be modified through the API after creation |
git config --show-origin --get-all credential.helper | View all assistants and sources | The first step in troubleshooting conflicts |
GIT_TRACE=1 GIT_CURL_VERBOSE=1 git … | Output HTTP and helper call details | Note that the output may contain tokens, do not send them out. |
git count-objects -vH、git rev-list --objects --all | git cat-file --batch-check | Find a big deal | See below |
git lfs ls-files / git lfs env | LFS status | Basis 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)
update_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.
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.
keep_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.git 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.git 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.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).
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"
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
- GitLab: Push mirroring (with AWS CodeCommit configuration steps)
- GitLab:Pull mirroring
- Remote mirrors API
- CodeCommit troubleshooting
Video storyboard (approx. 75 seconds)
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.
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.
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.
Module 8 · Migration, Costs and Self-Testing
- 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.
What: Two types of data to be migrated
| data | How to move | Tools |
|---|---|---|
| Git references and objects (branch, tag, full history) | git clone --mirror→ only pushrefs/heads/* with refs/tags/* | Git itself |
| PR/MR, Review, Issue, Wiki, Release | Platform importer or API | GitLab's GitHub importer (migrate PR → MR, Issue, etc.); "Import repository through URL" only migrates Git data |
| LFS object | git lfs fetch --all → git lfs push --all | The target must support LFS (CodeCommit does not support it as of verification date) |
| Permissions, branch protection, approval, CODEOWNERS semantics | Reconfigure according to the target platform (comparison table of M3/M5/M6 in this lesson) | IaC: gitlab/aws provider for Terraform |
| Pipeline, Webhook, Integration | Rebuild; switch to CodeConnections on AWS side | Lesson 5 |
Why: Why not directlygit push --mirror
- Hide reference: Cloning from the GitHub image will bring
refs/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)
- Freeze window announcement; source repository set to read-only (GitHub archive, Azure Repos disabled repository, GitLab archive, CodeCommit with IAM Deny).
git clone --mirrorSource repository; if LFS is available,git lfs fetch --all。- Create an empty repository on the target,Not yetEnable branch protection and push rules (or allow migration accounts to bypass).
- push
refs/heads/*withrefs/tags/*(CodeCommit batches by ≤ 4000 references). - Verification: number of branches/labels, consistent SHA of each branch,
git fsck。 - Import platform data (importer), rebuild protection, approval, CODEOWNERS (CodeCommit has no CODEOWNERS, use approval rule template instead), Webhook/connection.
- Developer execution
git remote set-url origin …;The source repository remains read-only for a period of time or reverse mirrored for rollback.
CodeCommit cost
| Project | content (withOfficial pricing pageshall prevail) |
|---|---|
| free tier | Effective 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 users | Official 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) |
| excess | storage $0.06/GB-month;Git request$0.001/time |
| active user definition | Visited 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 fees | VPC 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.
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
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).
Migration command
| command | function |
|---|---|
git clone --mirror URL repo.git | Complete 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 3000 | Split references by batch (CodeCommit ≤ 4000/time) |
git lfs fetch --all / git lfs push --all TARGET | Migrate LFS objects (must be supported by target) |
glab repo create/GitLab import interface | Create a target project or use the importer |
git remote set-url origin NEW | Developer 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)
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/tagsaws 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/*'
git cloneone sharegit fsck --full。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.
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
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
No verified "Cross-Platform Repository Migration" feature video found.
Official documentation
- Migrate a Git repository to CodeCommit
- How to migrate your CodeCommit repository to another Git provider (AWS Blog, 2024)
- GitLab:Import from GitHub
- CodeCommit pricing
- GitLab pricing
Video storyboard (approximately 60 seconds)
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.
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.
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.
Command cheat sheet
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=TOPICCodeConnections
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
| demand | CodeCommit | GitLab | GitHub (Lesson 3) | Azure Repos (Lesson 3) |
|---|---|---|---|---|
| Direct push to main is prohibited | IAM Deny + References + Null | Protected branch push=No one | ruleset | branching strategy |
| Approval required | Approval rule template | Approval Rules (Premium) | Number of rule set approvals | Minimum reviewers |
| path owner | — | CODEOWNERS(Premium) | CODEOWNERS | Automatically include reviewers |
| Commit Specifications/Prohibition of Confidential Documents | — (Self-built inspection required) | Push rules (Premium) | Rule Set Metadata Rules/Push Protection | — |
| Human certification recommended | GRC + Identity Center | OAuth(GCM/glab)/ PAT | GCM | GCM + Entra ID |
| LFS | Not supported (as of 2026-11-15) | support | support | support |
Comprehensive experiment: dual-platform protection + GitLab → CodeCommit push image
| Resources | cost | Required permissions | Cleaning method |
|---|---|---|---|
CodeCommit repositorymyapp、myapp-mirror | Free 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 templates | free | IAM administrator | Delete Credentials → Delete Inline Policy → Delete User → Detach and Delete Policy → Delete Template |
GitLab projectsalice-git-lab/myapp, mirror, PAT | Free | Group Owner | Delete image → Delete project → Undo PAT |
| (Optional) CodeConnections connection, SNS topic | Free / Free Tier | cc-admin | delete-connection、sns delete-topic |
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"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.
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.
myapp-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
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"
git 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
AVAILABLEDelete later.# 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.
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
| Topic | Verify conclusion | Source (Accessed on 2026-11-15) |
|---|---|---|
| CodeCommit status | No 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 method | Git 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://repo | Setting up · git-remote-codecommit |
| branch restriction strategy | Deny 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 role | Limit pushes and merges to branches |
| Approval rule template | Content 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 characters | Create an approval rule template· Quota page |
| Notifications and triggers | Notification 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 repository | Notification concepts · Trigger for SNS |
| CodeCommit quota | blob ≤ 2 GB; console/API/CLI single file ≤ 6 MB; single push ≤ 4000 references; repository ≤ 5000/account (adjustable); ca-central-1 is in the region list | Quota page |
| CodeCommit Pricing | The 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 |
| CodeConnections | Provider: 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 keys | Create a connection to GitLab · IAM reference |
| GitLab version | 19.5 released on 2026-10-15; released monthly | GitLab 19.5 release notes |
| GitLab protected branches | All 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 push | Protected branches |
| GitLab Approval / CODEOWNERS / Push Rules | The 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, DCO | Approval rules · Code Owners · Push rules |
| GitLab push image | All 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.