GitLab Hour 1: Core Fundamentals
- Explain GitLab.com / Self-Managed / Dedicated the three deployment models and Free / Premium / Ultimate the boundaries of the three tiers, so you can tell whether a feature is “available on my account”, and know what each GitLab component (Rails, Sidekiq, Gitaly, Workhorse, PostgreSQL, Redis) is responsible for.
- Use Group → subgroup → project to design an organizational structure, and to understand member inheritance, visibility restrictions, and how permissions differ across roles such as Minimal Access / Guest / Planner / Reporter / Developer / Maintainer / Owner.
- Use Issues, labels, milestones, boards, Epics to organize work, know which capabilities are Free and which require Premium, and understand that dragging a card on a board is essentially changing labels.
- Complete one full run-through Merge Request: creating a Merge Request, review threads, suggested changes, approvals, merge checks, auto-merge, the three merge methods and squash, and automatic closing of Issues after merging.
- Work fluently with glab to handle daily tasks, and use REST v4 and GraphQL to automate GitLab, understanding token types, scopes and rate limits.
- Be able to
mainconfigure branch rules, understand push rules and CODEOWNERS where checks happen on the server; use Wiki, notifications, search and GFM references to collaborate more efficiently; and finally complete one collaboration readiness review.
1-hour time allocation table
| # | Time | Module | Core content | Animation / interaction | Lab (GitLab.com Free) |
|---|---|---|---|---|---|
| 0 | Before class | Environment setup | GitLab.com account, 2FA, SSH key, PAT, glab installation and sign-in | Environment self-check checklist | glab auth status Pass |
| 1 | 00–06 | Platform overview | Three deployment models, three tiers, release cadence, component architecture, GitLab.com limits | Request path simulator: which components Web / API / git over SSH / git over HTTPS pass through | Check version, tier and usage |
| 2 | 06–13 | Groups, subgroups, projects and roles | Namespace hierarchy, member inheritance, visibility, default roles and custom roles | Permission evaluator: inheritance chain + action → allow/deny | Create mygroup-lab, subgroups and mygroup-lab/myapp |
| 3 | 13–21 | Issues, Epics, Boards and milestones | Work items, labels (including scoped labels), milestones, boards, Epics, quick actions | Board simulator: the label changes and API calls that actually happen when you drag a card | Create labels, milestone v1.0 and 3 Issues for myapp |
| 4 | 21–28 | Merge Request end to end | Review threads, suggestions, approvals, merge checks, auto-merge, merge methods and squash, closing Issues | Core animation: the platform event flow of one MR from push to merge | Use an MR to deliver myapp’s /healthz |
| 5 | 28–35 | glab and the REST / GraphQL API | common glab commands,glab api, REST pagination, GraphQL, tokens and rate limits | REST vs GraphQL call counts and rate-limit counters | Use the API to generate an “open MR report” |
| 6 | 35–42 | Protected branches, push rules and CODEOWNERS | Branch rules, protected tags, push rules (Premium), CODEOWNERS syntax and approvals | Server-side push check simulator: pre-receive → access check → push rules | Protect main, add CODEOWNERS and verify a rejected push |
| 7 | 42–50 | Wiki, notifications, search and productivity | Wiki repository, notification levels, to-dos, three search types, GFM references, keyboard shortcuts, description templates | GFM reference parser: recognizes #, !, ~, %, @, & as you type | Write a runbook wiki, MR template, adjust notifications |
| 8 | 50–60 | Collaboration readiness review and troubleshooting basics | 12 readiness checks, common errors (rejected push, 401/403/404, MR cannot be merged) | Readiness scorecard + interactive troubleshooting tree | Automatically review myapp with a glab api script |
| — | After class | Cheat sheet · Integrated lab | Build a “collaboration-ready” myapp project from scratch, preparing for Lesson 2’s CI/CD | Final quiz (12 questions) | Integrated lab |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / locations | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Determine the required tier and deployment model for a feature | ✓ | ✓ | ✓ | ✓ | · | ✓ | ✓ | ✓ | Tier/Offering label at the top of the docs page | M1 usage page |
| Design group hierarchy and member permissions | · | ✓ | · | · | ✓ | ✓ | · | ✓ | glab api groups, members page | mygroup-lab |
| Plan work with Issues / labels / milestones / boards | · | · | ✓ | ✓ | ✓ | · | ✓ | · | glab issue,glab label, quick actions | Milestone v1.0 |
| Complete MR review, approval and merge | · | · | · | ✓ | ✓ | ✓ | · | ✓ | glab mr create/approve/merge, push options | /healthz MR |
| Automate with glab and the API | ✓ | ✓ | ✓ | ✓ | ✓ | · | · | ✓ | glab api,curl, GraphQL | MR report / readiness script |
| Protect the default branch, configure code owners | · | ✓ | · | ✓ | · | ✓ | · | ✓ | Branch rules, CODEOWNERS | Rejected push |
| Knowledge capture and information retrieval | · | · | ✓ | · | · | · | ✓ | · | Wiki, search, GFM | Runbook |
| Diagnose common GitLab collaboration errors | ✓ | ✓ | · | ✓ | ✓ | ✓ | · | ✓ | GIT_TRACE,glab api -i | Troubleshooting tree |
Topics not covered in this lesson (and where to learn them)
| Topic | Why not in this lesson | Where to learn |
|---|---|---|
| Git internals, branching strategy, SSH/HTTPS authentication details, GitLab mirroring | Covered in the Git course | Git 8-hour course, GitLab part in Lesson 4 |
.gitlab-ci.yml, Runner, caching and artifacts, components | Belongs to the CI/CD topic | Lesson 2 |
| Container registry, OIDC deployment to Azure / AWS | Requires the pipeline basics from Lesson 2 | Lesson 3(Azure),Lesson 4(AWS) |
| Security scanning, compliance frameworks, audit events, GitLab Duo | Most require Ultimate; advanced topics | Lessons 5–7 (published later) |
| Self-Managed installation, backup, upgrade and high availability | This lesson focuses mainly on GitLab.com | Official installation docs, operations perspective in Lessons 6–7 |
| Comparison with GitHub Actions, Azure Pipelines, Jenkins | This lesson only does a conceptual comparison | GitHub · Azure DevOps · Jenkins |
How to use this course material
Principles · Diagrams · Animation · Commands · Lab · Production case · Troubleshooting · Quiz · Audio · Video. We recommend reading “Principles” and “Animation” first, then doing the “Lab”. The labs can be completed on a free GitLab.com account.
A quiz score of ≥ 70%, or clicking “Mark this module complete”, counts toward progress. Progress is saved in this browser’s local storage (refreshing clears it in private browsing mode or when storage is disabled).
The “Audio” page uses the browser’s built-in Web Speech API (en-US) to read the script aloud; if no Chinese voice pack is installed, the script can still be read, or passed to another TTS tool.
Course-wide conventions (shared by Lessons 1–8)
| Item | Convention |
|---|---|
| Platform | Mainly a free GitLab.com account; features that require Premium / Ultimate are labeled with their tier and come with a trial or Free alternative; Self-Managed differences are noted separately |
| Naming | Top-level group <your-username>-lab (written in the text as mygroup-lab); project mygroup-lab/myapp; default branch main; glab Signed in |
| Sample application myapp | Python Flask + gunicorn + Redis counter,port 5000,/healthz, pytest tests and a Dockerfile (created in this lesson’s lab; images built from Lesson 2 onward registry.gitlab.com/mygroup-lab/myapp, tag 1.0 / 1.1) |
| Following lessons | Lesson 2 Runner: local containers gitlab-runner, tag lab-docker; Lesson 3 Azure: rg-gitlab-lab / canadacentral; Lesson 4 AWS: ca-central-1 / ECR myapp |
Module 0 · Environment setup (complete before class)
- Completed Git 8-hour course: Git 2.4x installed locally, able to generate an SSH key, understanding branches and rebase.
- Work machine: Ubuntu 24.04 / macOS / Windows (WSL2 Ubuntu recommended). If you already installed Docker Engine in the Docker course, you can reuse it; this lesson’s lab does not need Docker; it is needed from Lesson 2 onward.
- An email address that can receive mail. GitLab.com registration may require email verification. When using GitLab-hosted runners, a free account may also be asked to verify its identity (for example, phone number or credit card; follow the prompts on the sign-up page; Lesson 2 explains this in detail).
Step 1: Sign up for GitLab.com and enable two-step verification
- Open gitlab.com/users/sign_up to sign up. Your username appears in every URL (for example
gitlab.com/alice), so choose a name you can keep using long-term at work. - Avatar menu → Edit profile → Account → Two-factor authentication, enable 2FA with a TOTP app or WebAuthn device, and download recovery codes and save them in a password manager.
- This lesson’s top-level group will be named
<your-username>-lab. Top-level group paths are globally unique on GitLab.com, so themygroup-labin the text is only an example; replace it with your own.
Step 2: SSH key (reuse the Git course key or create a new one)
# Skip ssh-keygen if you already have a key ssh-keygen -t ed25519 -C "you@example.com" -f ~/.ssh/id_ed25519_gitlab cat ~/.ssh/id_ed25519_gitlab.pub # Copy to Edit profile → SSH Keys, and set an expiration date cat >> ~/.ssh/config <<'EOF' Host gitlab.com HostName gitlab.com User git IdentityFile ~/.ssh/id_ed25519_gitlab IdentitiesOnly yes EOF ssh -T git@gitlab.com
Welcome to GitLab, @alice!
Step 3: Create a personal access token (PAT)
Edit profile → Access tokens → Add new token. Name glab-lab, set the expiration date within 30 days, and select the scope api (it already includes repository read/write permissions). The token starts with glpat- , and is shown only once.
api scope with a classic PAT; Module 5 explains how to choose narrower permissions.Step 4: Install and sign in to glab
glab is the official GitLab CLI (project gitlab-org/cli). The officially supported installation methods are Homebrew (macOS, Linux, WSL on Windows) or downloading a binary from the releases page; other package managers are community-maintained. Follow installation_options.md for details.
# macOS / Linux / WSL (Homebrew) brew install glab glab version # Option A: interactive sign-in (choose gitlab.com → Token or Web) glab auth login # Option B: non-interactive (suitable for scripts); the token is read from standard input to avoid entering shell history read -rs GLTOKEN && echo "$GLTOKEN" | glab auth login --hostname gitlab.com --stdin --git-protocol ssh unset GLTOKEN glab auth status
glab version 1.130.0 (2026-11-10) gitlab.com ✓ Logged in to gitlab.com as alice (keyring) ✓ Git operations for gitlab.com configured to use ssh protocol. ✓ API calls for gitlab.com are made over https protocol. ✓ REST API Endpoint: https://gitlab.com/api/v4/ ✓ GraphQL Endpoint: https://gitlab.com/api/graphql/ ✓ Token found: **************************
By default, glab stores the token in the operating system’s keyring. The token is written to the config file in plain text only when you add --insecure-storage does the token get written as plain text to the config file. Headless servers can use glab auth login --web --device (OAuth device flow, requires GitLab 17.9+). glab auth status The exact output format varies slightly between versions.
Step 5: Set environment variables (used throughout the course)
export GL_USER=$(glab api user | python3 -c 'import sys,json;print(json.load(sys.stdin)["username"])')
export GL_GROUP="${GL_USER}-lab" # written as mygroup-lab in the text
export GL_PROJECT="${GL_GROUP}/myapp"
echo "$GL_USER $GL_GROUP $GL_PROJECT"
# Add to ~/.bashrc so it is still available when you open a new terminal
printf 'export GL_GROUP=%s\nexport GL_PROJECT=%s\n' "$GL_GROUP" "$GL_PROJECT" >> ~/.bashrc
Warm-up: answer from memory (30 seconds)
What are GitHub’s Organization, Repository and Pull Request called in GitLab?
Roughly: top-level group (Group, which can nest subgroups), project (Project, which has more than a repository, including Issues, Wiki, CI/CD, Registry and so on), and Merge Request (MR). GitLab MR numbers are referenced with ! , and Issues are referenced with # .
After enabling 2FA, using HTTPS git push what happens if you enter your account password?
Authentication fails. HTTPS requires a personal access token (or a credential helper configured by glab) instead of a password; SSH is recommended.
Module 1 · GitLab platform overview: deployment models, tiers and architecture
- Distinguish GitLab.com (multi-tenant SaaS), GitLab Self-Managed (you operate it yourself), and GitLab Dedicated (single-tenant SaaS, hosted on AWS).
- Remember the key boundaries of Free / Premium / Ultimate and the hard limits of the GitLab.com free tier (5 users, 10 GiB, 400 compute minutes).
- Describe how a web request, an API request,
git pushand a git request each pass through components among Workhorse, Puma (Rails), Gitaly and Sidekiq.
What: what GitLab is
GitLab is a single application DevSecOps platform: the same Rails application and the same PostgreSQL database store Issues, Merge Requests, pipelines, container registry metadata, security scan results and deployment environments together. This differs from a toolchain assembled from “GitHub + Jira + Jenkins + Artifactory”: cross-feature links (Issue ↔ MR ↔ pipeline ↔ deployment) are database-level foreign keys and do not need plugin synchronization.
GitLab’s code is released using an open-core model: CE (Community Edition) is the MIT-licensed open-source edition; EE (Enterprise Edition) includes all the code; without a license it has the same features as Free, and activating a Premium / Ultimate license unlocks paid features. GitLab.com runs EE.
Why: why you need to understand deployment models and tiers first
In the same documentation, almost every page has at the top Tier (Free / Premium / Ultimate) and Offering (GitLab.com / GitLab Self-Managed / GitLab Dedicated) labels. Many questions like “why can’t I find this setting” have the answer that the tier is not sufficient (for example, push rules, required approvals and scoped labels all need Premium), or the deployment model is wrong (for example, GitLab.com does not offer Internal visibility and does not allow server-side Git hooks).
How: three deployment models
| GitLab.com | GitLab Self-Managed | GitLab Dedicated | |
|---|---|---|---|
| Model | Multi-tenant SaaS operated by GitLab | You install and operate it on your own servers / cloud / Kubernetes | Operated by GitLab as a single-tenant SaaS with fully isolated instances |
| Tiers | Free / Premium / Ultimate | Free (CE or unlicensed EE) / Premium / Ultimate | Ultimate |
| Upgrades | Continuously deployed, always up to date | You upgrade yourself (one minor version per month, following the upgrade path) | Maintained by GitLab on a schedule |
| Hosting location | GitLab’s cloud | Anywhere (Linux packages, Helm Chart, Operator, Docker) | AWS, customer chooses the region; customer-owned AWS KMS keys can be used; Azure / GCP not supported |
| Admin rights | None (you can only manage your own groups) | Full instance administrator (Admin area) | Limited instance configuration (through Switchboard, etc.) |
| Typical reasons to choose | Fastest to start, zero operations | Data must stay on the internal network; server-side hooks / customization needed | Needs data residency and isolation, but does not want to operate it |
How: key boundaries of the three tiers (GitLab.com, verified 2026-11)
| Free | Premium | Ultimate | |
|---|---|---|---|
| Price | $0 | $29 / user / month (billed annually) | Contact sales (custom pricing) |
| Compute minutes (hosted runners, per month / per top-level namespace) | 400 | 10,000 | 50,000 |
| Storage | Repository (including LFS) limit 10 GiB | 500 GiB per project | 500 GiB per project |
| Users | Private Top-level group has up to 5 users; beyond that it becomes read-only (public groups are not limited) | Per seat | Per seat |
| Code review and protection | Optional approvals, protected branches, auto-merge, three merge methods | Required approvals / approval rules, CODEOWNERS approvals, push rules, merge trains, group-level protected branches | + security approval policies, compliance frameworks |
| Planning | Issues, labels, milestones, multiple project boards | Epics, scoped labels, iterations, weights, configurable boards | + sub-Epics, health status, OKRs, etc. |
| Security | Some scanners (limited result display) | Same as Free | Full security dashboard, vulnerability management, custom roles |
Pricing, minutes and storage come from about.gitlab.com/pricing and docs.gitlab.com (accessed 2026-11-16) and may change at any time; check the official pages before purchasing. If you do not have a paid tier, you can request an Ultimate trial (trial period and limits as shown in the interface) to try the features this lesson labels as Premium.
How: component architecture (what a request passes through)
| Component | Responsibility |
|---|---|
| NGINX / load balancer | TLS termination, forwards to Workhorse |
| GitLab Workhorse (Go) | Smart reverse proxy: handles git clone/push over HTTPS, large file uploads and downloads, and artifacts, offloading the “heavy lifting” from Rails |
| Puma (Rails application) | Web UI, REST API v4, GraphQL API; permission checks and business logic all live here |
| Sidekiq | Background jobs: sending notification emails, creating pipelines, handling post-push follow-ups (closing Issues, updating MRs), webhooks |
| Gitaly (Go, gRPC) | All Git repository reads and writes go through it; Rails never accesses repositories on disk directly. Gitaly Cluster (Praefect) provides replication and high availability |
| GitLab Shell / gitlab-sshd | Handles git@gitlab.com:… SSH connections, asking the Rails internal API “can this key access this project” |
| PostgreSQL / Redis | Primary data / cache, sessions, Sidekiq queues |
| Object storage | Artifacts, LFS, uploaded files, packages, image layers |
| Others | Container Registry, GitLab Pages, KAS (server side of the GitLab agent for Kubernetes, Lesson 6), Runner (deployed separately, Lesson 2) |
When: how to choose
- Learning, personal projects, startup teams: GitLab.com Free. Note that the 5-user limit applies only to private top-level groups.
- Teams that need required approvals, push rules, Epics: GitLab.com Premium, or Self-Managed + Premium license.
- Regulated industries, data must be in a specified region, but no desire to operate: Dedicated; Must run on an internal network or offline: Self-Managed (can be installed offline).
- Needs server hooks, custom Admin settings, Internal visibility: Self-Managed / Dedicated only.
Comparison with similar platforms
| GitLab | GitHub | Azure DevOps | |
|---|---|---|---|
| Organization structure | Groups can nest up to 20 levels of subgroups | Enterprise → Organization → Repo (no nesting) | Organization → Project → multiple Repos |
| Code review unit | Merge Request (!1) | Pull Request (#1) | Pull Request |
| CI/CD | Built-in .gitlab-ci.yml + Runner | GitHub Actions | Azure Pipelines |
| Self-hosted | Self-Managed (CE free) | GitHub Enterprise Server (paid) | Azure DevOps Server |
For comparison:GitHub 8-hour course · Azure DevOps 8-hour course.
Architecture diagram: GitLab’s main components
Decision chart: can I use this feature?
Request path simulator: one GitLab, four entry points
Choose an operation and play it. The highlighted box is the component currently handling the request; the log below shows the corresponding real request, internal API or gRPC call (log format is illustrative; interface names come from the GitLab architecture docs).
Key takeaway: no matter which entry point you come through,Rails always decides “whether it is allowed” (SSH also calls the internal API /api/v4/internal/allowed); Git data is always read and written by Gitaly; the “chain reaction” after a push (pipelines, closing Issues, notifications) is completed asynchronously by Sidekiq, so it is normal for a pipeline to appear a few seconds after a successful push.
Core commands and locations
| Command / location | Purpose | Notes |
|---|---|---|
glab api version | View instance version (requires authentication) | Returns version,revision,enterprise |
glab api metadata | More detailed metadata (including KAS information) | Requires authentication; also applies to Self-Managed |
glab api namespaces | View your namespaces and their plan | On GitLab.com, returns plan field (free / premium / ultimate, etc.) |
| Group → Settings → Usage quotas | Compute minutes, storage and seat usage | Visible to Owner |
https://gitlab.com/help | View version on the web | Visible after signing in |
sudo gitlab-rake gitlab:env:info | Self-Managed: environment and version information | Linux package installation |
glab api version
glab api namespaces | python3 -c 'import sys,json; [print(n["full_path"], n["kind"], n.get("plan")) for n in json.load(sys.stdin)]'
{"version":"19.5.6-ee","revision":"3f9c2a1b7e4","kas":{"enabled":true,"externalUrl":"wss://kas.gitlab.com","version":"19.5.6"},"enterprise":true}
alice user free
How to verify: Self-Managed returns the installed release version (for example 19.5.6). GitLab.com deploys continuously, so the version string returned may differ from the latest release; go by the actual output. Common errors: Calling it directly without a token curl https://gitlab.com/api/v4/version returns 401 Unauthorized. Production use: Use it before and after Self-Managed upgrades to confirm the version; scripts use plan to check whether a given Premium API is available.
Without glab, use curl
curl -s --header "PRIVATE-TOKEN: $GITLAB_TOKEN" https://gitlab.com/api/v4/version # Equivalent form (OAuth-style header; PATs are also supported) curl -s --header "Authorization: Bearer $GITLAB_TOKEN" https://gitlab.com/api/v4/version
Quick Self-Managed trial (optional, local testing only)
# Official Docker image; the first startup takes several minutes and needs at least 4 GB of memory docker run --detach --hostname gitlab.local --name gitlab-sm \ --publish 8443:443 --publish 8080:80 --publish 2222:22 \ --volume ~/gitlablab/sm/config:/etc/gitlab --volume ~/gitlablab/sm/logs:/var/log/gitlab \ --volume ~/gitlablab/sm/data:/var/opt/gitlab --shm-size 256m gitlab/gitlab-ee:latest docker exec -it gitlab-sm grep 'Password:' /etc/gitlab/initial_root_password # Cleanup: docker rm -f gitlab-sm && sudo rm -rf ~/gitlablab/sm
In production, pin the image tag to a specific version (for example gitlab/gitlab-ee:19.5.6-ee.0; check Docker Hub for the tag format). The later labs in this lesson are all completed on GitLab.com; this step only shows you the Admin area and the “instance administrator” view.
Lab 1: Give your GitLab environment a “checkup” (about 4 minutes)
glab api version glab api user | python3 -c 'import sys,json;u=json.load(sys.stdin);print(u["username"], u["two_factor_enabled"], u["created_at"][:10])'
{"version":"19.5.6-ee", ...}
alice True 2026-11-16
two_factor_enabled should be True, otherwise go back to Module 0 and enable 2FA.
glab api namespaces of your personal namespace in plan should show free. After the group is created (Module 2), its plan will also appear here.api or read_api); risk: do not paste tokens into screenshots or chat logs.Case 1: A startup begins on Free; when the 6th person joins, the project becomes read-only
Problem: After the 6th member joins a private top-level group on the Free tier, all pushes fail and the UI shows that the namespace is read-only. Solution: The Free user limit is counted across all subgroups and projects within the top-level group, as unique users. First remove inactive members to restore write access, then evaluate upgrading to Premium. Configuration: Group → Settings → Usage quotas → Seats to view usage. Limitation: Public top-level groups are not subject to the 5-user limit, but their code is public, so they are not suitable for commercial projects.
Case 2: A financial customer chooses Dedicated instead of Self-Managed
Problem: Regulations require data residency in the Canada region, and the team cannot run the Gitaly cluster and PostgreSQL 24×7. Solution: Choose GitLab Dedicated, deployed in the AWS region the customer selects, and encrypted with the customer’s own KMS keys. Limitation: Dedicated is only offered on AWS and only at the Ultimate tier; if Azure is required, Self-Managed is needed (deployed on AKS with a Helm Chart or Operator; see the AKS course).
Case 3: Why “Internal” visibility cannot be found on GitLab.com
Problem: A team migrating from Self-Managed to GitLab.com found that projects previously set to Internal cannot keep that level on .com. Solution: On GitLab.com, use a private group + member inheritance to achieve “visible within the company”, and use group sharing to grant access to other departments when needed. Limitation: Internal is only available on Self-Managed and Dedicated.
Common errors and fixes
{"message":"401 Unauthorized"} (request to /api/v4/version)
Cause: This endpoint requires authentication; or the token has expired, been revoked, or lacks the required scope.
glab auth status
curl -s -o /dev/null -w '%{http_code}\n' --header "PRIVATE-TOKEN: $GITLAB_TOKEN" https://gitlab.com/api/v4/user
Fix: Generate a new token with at least the read_api scope, then re-run glab auth login.
A setting described in the docs is missing from my project (for example, there is no Push rules under Settings → Repository)
Cause: Check in order, as in Figure 1-2: Offering, Tier (check the top-level group’s subscription), role (most settings require Maintainer), and feature flags.
glab api namespaces | grep -o '"full_path":"[^"]*","[^}]*"plan":"[^"]*"'
Fix: Upgrade or request a trial; or use the Free alternative given in this lesson (for example, use a CI job to check commit messages instead of push rules; see Module 6).
Your top-level group is over the user limit and has been placed in a read-only state. (UI message; the wording may differ slightly.)
Cause: A private top-level group on the Free tier has more than 5 unique users.
Fix: Group → Settings → Usage quotas → Seats to view and remove members, or upgrade / change to a public group (this makes the code public, so think carefully).
Self-Managed upgrade failed: a required upgrade stop was skipped
Cause: When upgrading across multiple major versions, you must pass through specified intermediate versions to complete background migrations.
Fix: Plan the path according to the official Upgrade paths documentation (including the upgrade path tool link); check after each step that Admin → Monitoring → Background migrations has completed before continuing.
1. Use one glab command to check the version of your GitLab instance.
glab api version
2. Use curl (not glab) to look up the username for the current token.
curl -s --header "PRIVATE-TOKEN: $GITLAB_TOKEN" https://gitlab.com/api/v4/user | python3 -c 'import sys,json;print(json.load(sys.stdin)["username"])'
A healthcare company requires: data must be in the AWS Canada region, it needs security scanning and vulnerability management, and its IT team has only 2 people. Which deployment model and tier do you recommend? Why not GitLab.com Ultimate?
I recommend GitLab Dedicated (offered only at Ultimate, which covers security scanning and vulnerability management). It is single-tenant, deployed in the AWS region the customer chooses, can use the customer’s own KMS keys, and is operated by GitLab, which fits “data residency + small staff”. GitLab.com is multi-tenant and the customer cannot choose where data is located; Self-Managed requires you to operate PostgreSQL, Gitaly, upgrades and backups yourself, which is too much for a 2-person team.
Verified instructional videos
Official documentation
Video storyboard (about 90 seconds)
This course material cannot generate video or MP3 directly; the storyboard and narration script are provided so they can be handed to a video tool.
Visual: three cloud icons side by side labeled GitLab.com, Self-Managed, Dedicated; below them are “multi-tenant”, “you operate it”, and “single-tenant AWS”.
Narration: One GitLab, three ways to use it: the multi-tenant GitLab.com, the self-operated Self-Managed, and the single-tenant Dedicated hosted by GitLab.
Visual: a three-step staircase, Free, Premium, Ultimate; each step lights up with representative feature icons (approval rules, push rules, vulnerability dashboard).
Narration: The tier is determined by the top-level group’s subscription. Required approvals and push rules start at Premium; the full security dashboard is in Ultimate.
Visual: a dot representing a git push travels from the client through Shell, Rails and Gitaly; Sidekiq then branches off two side paths, “pipelines” and “notifications”.
Narration: Rails decides whether something is allowed, Gitaly reads and writes Git data, and Sidekiq handles the follow-on chain reaction.
Visual: the Tier and Offering lines at the top of a docs page are zoomed in and highlighted.
Narration: When you cannot find a setting, check these two lines at the top of the docs page first.
Module 2 · Groups, subgroups, projects and role permissions
- Design an organizational structure with top-level group → subgroup → project, and explain
mygroup-lab/myappthe meaning of each segment in this path. - Remember the order of the default roles and the key capability differences, especially the boundaries between Planner, Reporter and Developer, and between Maintainer and Owner.
- Master group-level governance tools such as member inheritance, group sharing, visibility constraints and 2FA enforcement.
What: the three kinds of namespace nodes
- Personal namespace:
gitlab.com/alice, suitable for personal experiments; not recommended for team projects (projects leave with the person when they depart). - Group: a top-level group is the boundary for subscription, billing, SSO and the user limit; Subgroup can nest up to 20 levels; the official recommendation is no more than 5 levels to avoid performance problems.
- Project: one Git repository + Issues + MRs + Wiki + CI/CD + package and container registries, etc. The project path is the parent namespace path + project path, for example
mygroup-lab/platform/infra.
Why: why use groups instead of adding people to each project individually
Group members automatically inherit to all subgroups and projects; onboarding or offboarding requires changing only one place. CI/CD variables, runners, labels, milestones, Epics, protected branch rules (Premium) and compliance settings can all be defined at the group level and inherited downward. The Lesson 2 runner will be registered at the mygroup-lab group level, so all projects in the group can share it.
How: default roles (from lowest to highest)
| Role | Typical users | Key capabilities (project level) |
|---|---|---|
| Minimal Access | People who only need to appear in the group member list (for example, a placeholder for auditors) | Almost no permissions; mainly used for SSO / seat management; can only be used in a top-level group, and requires Premium / Ultimate |
| Guest | External stakeholders | Create Issues and comment; in private projects,cannot see code by default |
| Planner (introduced in 17.7) | Product managers, project managers | Create / edit Issues, Epics, milestones and Wiki pages, view confidential Issues; since 18.7 can pull code; cannot push |
| Reporter | QA, read-only developers, operations | Pull code, manage labels and milestones, view pipelines; cannot push |
| Security Manager (18.11 Beta) | Security team | Security-related capabilities; sits between Reporter and Developer but is not a strict superior/subordinate level |
| Developer | Developers | Push to non-protected branches, create MRs, approve MRs, run pipelines; by default cannot push to or merge into protected branches |
| Maintainer | Tech leads | Push to / merge into protected branches, change project settings and branch rules, add project members |
| Owner | Group administrators | Delete / archive projects, manage group settings and all members, billing |
Planner and Security Manager are “specialized roles” and do not include all permissions of the roles below them (for example, Planner can edit Wiki pages but Reporter cannot; Reporter can pull packages and create snippets, but Planner cannot). The full permission matrix is in Roles and permissions. Custom roles (Ultimate) add fine-grained permissions on top of a default role; on GitLab.com they are created by the top-level group Owner, and on Self-Managed / Dedicated by the instance administrator.
How: inheritance and override rules
- Group members enter all subgroups and projects with the same role (shown on the members page as Inherited).
- In a subgroup / project,you can only grant a higher role: “You can't give a user a role in a subgroup that is lower than the roles the user has in parent groups.” To give someone lower permissions in a project, you can only remove them from the upper level and then add them directly where needed.
- Group sharing (Invite a group): invite an entire group into another project / group with a chosen “maximum role”; members’ effective role is the lower of the two. Suitable for “the platform team has Reporter access to all business projects”.
- Members can set an expiration date, after which they are removed automatically (suitable for contractors and temporary access).
How: visibility
Private (members only) / Internal (all signed-in users; GitLab.com does not offer it) / Public (anyone). A project’s visibility cannot be more open than its parent group’s: you cannot create a public project under a private group.
When: recommended structure
mygroup-lab/ ← Top-level group: subscription, SSO, 2FA enforcement, group runners, global labels
├── myapp ← Sample project for this course (Lessons 1–8)
└── platform/ ← Subgroup: platform team; Maintainers are only here
└── infra ← e.g., Terraform / Helm configuration (optional in later lessons)
Comparison with similar platforms
| GitLab | GitHub | Azure DevOps | |
|---|---|---|---|
| Hierarchy | Groups can nest | Organization + Teams (teams can nest; repositories do not) | Organization → Project |
| Roles | Guest/Planner/Reporter/Developer/Maintainer/Owner | Read/Triage/Write/Maintain/Admin | Readers/Contributors/Project Administrators (security groups) |
| Fine-grained | Custom roles (Ultimate) | Custom repository roles (Enterprise) | Per-object ACLs |
main is a protected branch, so by default only Maintainers can merge (adjustable in Module 6). ③ “Guests can see the code of private projects”: not by default. ④ “Planner has fewer permissions than Reporter, so it is a subset of Reporter”: no, they are specialized roles that go in different directions.Structure diagram: member inheritance in mygroup-lab
Permission ladder: which actions require which role
Permission evaluator: inheritance chain + action → allow / deny
Set three levels of membership for bob, choose an action, and click “Evaluate”. The simulator calculates, following GitLab’s rules,the effective role (the higher of direct and inherited membership; the lower for group sharing), then checks the permissions table. The log shows the corresponding fields you can see in the API.
Core commands
| Command | Purpose | Key parameters / notes |
|---|---|---|
| Web: New group | Create top-level group | On GitLab.com, top-level groups can only be created in the UI (the API does not allow it) |
glab api groups -X POST | Create subgroup | -f name= -f path= -F parent_id= |
glab repo create GROUP/NAME | Create project | --private,--defaultBranch main,--readme,-d description |
glab api groups/:id/members -X POST | Add members | -F user_id= -F access_level=30 -f expires_at=YYYY-MM-DD |
glab api projects/:id/members/all | List all members, including inherited ones | /members Returns direct members only |
glab api projects/:id/share -X POST | Share a group with a project | -F group_id= -F group_access=20 |
access_level values: 5 Minimal Access,10 Guest,15 Planner,20 Reporter,30 Developer,40 Maintainer,50 Owner; Security Manager is 25 (see Members API; 5 available only in top-level groups with Premium / Ultimate).
# Look up the top-level group ID (the group must first be created in the UI) GID=$(glab api "groups/$GL_GROUP" | python3 -c 'import sys,json;print(json.load(sys.stdin)["id"])') echo $GID # Create subgroup platform glab api groups -X POST -f name=platform -f path=platform -F parent_id=$GID -f visibility=private
81234567
{"id":81234601,"name":"platform","path":"platform","full_path":"mygroup-lab/platform","parent_id":81234567,"visibility":"private",...}
# List all project members (including inherited), showing the source glab api "projects/$(printf %s "$GL_PROJECT" | sed 's#/#%2F#g')/members/all" | \ python3 -c 'import sys,json; [print(m["username"], m["access_level"]) for m in json.load(sys.stdin)]'
alice 50
How to verify: In the members page, the Source column shows whether the member is direct or inherited, and from which group. Common errors: The / in the project path must be URL-encoded as %2F (or use the glab :id,:fullpath placeholder in the project directory). Production use: Periodically export members/all for access reviews (Module 8).
Lab 2: Create mygroup-lab, the platform subgroup and the myapp project (about 6 minutes)
<your-username>-lab (i.e. $GL_GROUP), and select Visibility Private.
glab api "groups/$GL_GROUP" | python3 -c 'import sys,json;g=json.load(sys.stdin);print(g["id"], g["full_path"], g["visibility"])'
81234567 mygroup-lab private
GID=$(glab api "groups/$GL_GROUP" | python3 -c 'import sys,json;print(json.load(sys.stdin)["id"])') glab api groups -X POST -f name=platform -f path=platform -F parent_id=$GID -f visibility=private | python3 -c 'import sys,json;print(json.load(sys.stdin)["full_path"])'
mygroup-lab/platform
/healthz the tests are added later in Module 4 via an MR):
mkdir -p ~/gitlablab && cd ~/gitlablab
glab repo create "$GL_PROJECT" --private --defaultBranch main -d "GitLab 8-hour course sample app"
cd myapp 2>/dev/null || { git clone "git@gitlab.com:$GL_PROJECT.git" && cd myapp; }
git switch -c main 2>/dev/null || git switch main
cat > requirements.txt <<'EOF'
flask>=3.1
gunicorn>=23
redis>=5
EOF
cat > requirements-dev.txt <<'EOF'
-r requirements.txt
pytest>=8
EOF
cat > app.py <<'EOF'
import os
import socket
import redis
from flask import Flask, jsonify
app = Flask(__name__)
cache = redis.Redis(host=os.getenv("REDIS_HOST", "redis"), port=6379,
socket_connect_timeout=1, socket_timeout=1)
@app.get("/")
def index():
try:
hits = cache.incr("hits")
except redis.exceptions.RedisError:
hits = None # still responds when Redis is unavailable
return jsonify(app="myapp", version=os.getenv("APP_VERSION", "dev"),
host=socket.gethostname(), hits=hits)
EOF
mkdir -p tests
cat > tests/test_app.py <<'EOF'
from app import app
def test_index_without_redis(monkeypatch):
monkeypatch.setenv("APP_VERSION", "test")
resp = app.test_client().get("/")
assert resp.status_code == 200
assert resp.get_json()["app"] == "myapp"
EOF
cat > Dockerfile <<'EOF'
FROM python:3.13-slim
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
RUN useradd -r -u 10001 app
USER app
EXPOSE 5000
CMD ["gunicorn", "-b", "0.0.0.0:5000", "-w", "2", "app:app"]
EOF
printf '__pycache__/\n.venv/\n.pytest_cache/\n' > .gitignore
printf '# myapp\n\nFlask + gunicorn + Redis counter, port 5000.\n' > README.mdpython3 -m venv .venv && . .venv/bin/activate pip install -q -r requirements-dev.txt REDIS_HOST=127.0.0.1 pytest -q git add . && git commit -m "feat: initial myapp (Flask + Redis counter on port 5000)" git push -u origin main
. [100%] 1 passed in 1.12s ... To gitlab.com:mygroup-lab/myapp.git * [new branch] main -> main branch 'main' set up to track 'origin/main'.
Without a local Redis,/ returns "hits": null, and the tests still pass (connection timeout 1 second). The Lesson 2 pipeline will run the same tests in CI.
mygroup-lab:
UID2=$(glab api "users?username=COLLEAGUE" | python3 -c 'import sys,json;print(json.load(sys.stdin)[0]["id"])') glab api "groups/$GID/members" -X POST -F user_id=$UID2 -F access_level=30 -f expires_at=$(date -d '+30 days' +%F)
Note that the Free tier allows up to 5 unique users in a private top-level group. On macOS, the date uses date -v+30d +%F.
glab repo view "$GL_PROJECT" You can see the README. Do not delete mygroup-lab and myapp, because Lessons 2–4 build on them. If you only want to clean up the subgroup: glab api groups/$GL_GROUP%2Fplatform -X DELETE (group deletion may have a delayed deletion period).Case 1: A contractor team accessed repositories they should not see
Problem: Contractors were added to the top-level group as Reporters, so they could pull code from all subgroups. Solution: Remove them from the top-level group, add them directly only to the subgroups / projects they need, and set an expires_at expiration date; if the top-level group is used for SSO, Minimal Access can serve as a placeholder. Configuration: Quarterly access review script export members/all (Module 8). Limitation: Inherited roles cannot be lowered at a lower level, so the structure must be designed before granting access.
Case 2: A product manager wants to manage planning only, without code access
Problem: Previously the only options were Reporter (can pull code) or Guest (cannot see confidential Issues or edit Epics). Solution: Since 17.7, use the Planner role: it can manage Issues, Epics, milestones and Wiki. Limitation: Since 18.7 Planner can also pull code; if code access must be fully blocked, a custom role at Ultimate is needed.
Case 3: The platform team needs read-only access to all business projects
Problem: SREs need to view pipelines and code across 80 projects. Solution: Share the platform-sre group with each business group as Reporter (Invite a group), instead of adding people one by one. Limitation: The effective shared role is the lower of the “maximum role at invitation” and the member’s role in the original group.
Common errors and fixes
{"message":"403 Forbidden"} (POST /groups to create a top-level group)
Cause: On GitLab.com, top-level groups can only be created in the UI; or the account lacks permission to create groups.
Fix: Create top-level groups in the UI; use the API only to create subgroups (with parent_id).
{"message":{"access_level":["should be greater than or equal to Developer inherited membership from group mygroup-lab"]}}
Cause: Attempting to give a user a lower permission in a subgroup / project than their inherited role (error wording varies slightly by version).
glab api "projects/:id/members/all/USER_ID"
Fix: Adjust or remove them at the upper group, then add them directly at the lower level.
{"message":"404 Project Not Found"} (the project does exist)
Cause: Private projects return 404 instead of 403 to users without permission (so their existence is not revealed); or the path is not URL-encoded.
glab api "projects/$(printf %s mygroup-lab/myapp | sed 's#/#%2F#g')" | head -c 200
Fix: Confirm the token’s user is a member; check the %2F encoding; check the token scope.
Visibility level private is not allowed in a public group / project visibility … is not allowed
Cause: A project’s visibility cannot be more open than its parent group’s (it can be stricter).
Fix: Adjust the group’s visibility first, or move the project to a suitable group.
After signing in, members are asked to set up 2FA and cannot access the group
Cause: The group enforces 2FA and the grace period has expired.
Fix: Members set up 2FA under Edit profile → Account; the Owner can communicate with members during the grace period.
1. Under mygroup-lab , use the API to create a subgroup team-a.
GID=$(glab api groups/mygroup-lab | python3 -c 'import sys,json;print(json.load(sys.stdin)["id"])') glab api groups -X POST -f name=team-a -f path=team-a -F parent_id=$GID
2. List all members of myapp with a role of Maintainer or higher (including inherited).
glab api "projects/mygroup-lab%2Fmyapp/members/all" | python3 -c 'import sys,json; [print(m["username"]) for m in json.load(sys.stdin) if m["access_level"]>=40]'
bob, in mygroup-lab is a Developer. The team wants him, in platform/infra to be able to merge into main, but in myapp can only view code. How should this be designed?
“Can only view code” requires a role below Developer, but inherited roles cannot be lowered, so you must first remove bob from mygroup-lab ; then in myapp directly add him as Reporter, in platform (or platform/infra) directly add him as Maintainer. If many people need the same combination, create a infra-maintainers group and grant access with group sharing.
Verified instructional videos
No verified video specifically covering “group inheritance and roles” was found; a storyboard script is provided instead.
Official documentation
Video storyboard (about 80 seconds)
This course material cannot directly generate video or MP3; the storyboard and narration script are provided.
Visual: a tree with root node mygroup-lab, branching into myapp and platform; platform has infra beneath it.
Narration: GitLab organizes everything with groups. A top-level group is the boundary for subscriptions and billing, and subgroups can nest up to twenty levels.
Visual: bob’s avatar with a Developer badge flows from the root node to all child nodes; at platform the badge upgrades to Maintainer.
Narration: Members inherit downward. At lower levels, you can only add permissions, not remove them.
Visual: a seven-step staircase with Guest, Planner, Reporter, Developer, Maintainer and Owner, and typical actions labeled on each step.
Narration: Developers can push ordinary branches and create MRs; merging into the protected main branch requires Maintainer by default.
Visual: an attempt to create a public project inside a private group, with a red prohibition sign appearing.
Narration: A project’s visibility cannot be more open than its parent group’s.
Module 3 · Issues, Epics, Boards and milestones
- Set up a label system for myapp (type / workflow / priority), understand the difference between group labels and project labels, and scoped labels’
key::valuemutually exclusive behavior (Premium). - Use milestones to
v1.0plan deliveries, track progress with boards, and know what GitLab actually changes when you drag a card. - Understand the current status of Epics (Premium) as work items, and the Free-tier alternatives (parent Issue + sub-tasks, milestones).
- Use quick actions and
glab issue.
What: the Work items family
GitLab is unifying Issues, Tasks, Epics, Incidents, Objectives / Key Results and so on under the work item framework: the same set of fields (assignee, labels, milestone, due date, parent-child relationships, linked items) and the same “Work items” list view. Epics as work items were introduced as Beta in 17.2,18.1 GA (the feature flag was removed), so Epics and Issues now look and behave almost identically; Epic references can also be written as #123 or &123.
| Object | Scope | Level | Typical use |
|---|---|---|---|
| Issue | Project | Free | A deliverable requirement / defect that can be closed by an MR |
| Task | Project (child of an Issue) | Free | Splits an Issue into checkable small items; each Task can also have an assignee |
| Incident | Project | Free (some features paid) | Production incidents (Lessons 5–7) |
| Epic | Group | Premium; sub-Epics Ultimate | Cross-project themes / features, summarizing progress across multiple Issues |
| Milestone | Project or group | Free | Timebox: a release or sprint, with start / due dates and burndown data |
| Iteration | Group (iteration cadence) | Premium | Fixed-cycle sprints that roll over automatically |
| Label | Project or group | Free; scoped labels Premium | Categories, workflow states, priorities |
Why: why planning happens on a code platform
Because Issues, MRs, pipelines and deployments all live in the same database: write Closes #1, and the Issue closes automatically after merging into the default branch; the milestone page shows completion for both Issues and MRs; Value Stream analytics can measure from “Issue created” all the way to “deployed to production”.
How: three rules for labels
- Group labels can be used for Issues, MRs and Epics in the group, all its subgroups and projects; Project labels are used only in this project. Labels shared across the team belong at the group level.
- Scoped labels (Premium): the title contains
::, and only one label from the same scope (workflow::) can be on an object at a time; addingworkflow::reviewautomatically removesworkflow::doing. On the Free tier, labels with::are just ordinary labels, and do not mutually exclude each other. - Priority labels: star a label in the project label list to decide its order when sorting by “label priority”.
How: what an Issue board really is
- Each column is a query: Open (open Issues without any column label), a specific label column, and Closed.
- Dragging from label column A to label column B: removes label A and adds label B; dragging from Open to a label column adds the label; dragging back to Open removes it; dragging to Closed: closes the Issue (label changes do not happen).
- An Issue with several column labels appears in several columns at once.
- Free: a project can have multiple boards, a group can have only one board, and there is no “configurable board” (scoped by milestone / assignee) or assignee column; Premium: multiple group boards, configurable boards, assignee / milestone / iteration columns, WIP limits.
How: quick actions (typed in comments or descriptions)
| Quick action | Effect | Tier |
|---|---|---|
/assign me,/assign @bob | assign | Free |
/label ~bug ~"workflow::doing",/unlabel ~bug | add or remove labels | Free |
/milestone %v1.0 | set milestone | Free |
/due 2026-12-01,/estimate 2h,/spend 30m | due date, time tracking | Free |
/relate #2,/confidential,/close | link, confidential, close | Free |
/weight 3,/epic &5,/iteration *iteration:"Sprint 1" | weight, add to Epic, iteration | Premium |
When: how to simulate an Epic on the Free tier
Without Premium, you can use a “parent Issue” (label type::epic) + several Tasks or linked Issues to represent a theme, and use a group milestone to summarize progress across projects. Request a trial or upgrade only when you need a true Epic roadmap.
Comparison with similar tools
| GitLab | GitHub | Azure Boards | Jira | |
|---|---|---|---|---|
| Hierarchy | Epic → Issue → Task | Issue + sub-issues | Epic → Feature → User Story → Task | Epic → Story → Sub-task |
| Board column | labels / assignee / milestone / iteration | Projects Status field | Work item status | Workflow state |
| Timebox | Milestones, iterations | Milestone, Iteration fields | Iteration Path | Sprint |
workflow:: prefix automatically makes labels mutually exclusive”: mutual exclusion is a Premium feature. ③ “An Issue is closed as soon as an MR mentions it”: only with a closing keyword (Closes / Fixes / Resolves / Implements) and merged into the default branch closes it, and a project can turn this behavior off.Relationship diagram: Epic, Issue, Task, MR, milestone
Flow diagram: data changes when dragging on a board
Board simulator: dragging a card = changing labels
Click a card to select it, then click “Move here” on the target column. You can also type quick actions below. Turn on the “Premium scoped labels” switch and observe /label ~"workflow::review" the different results under Free and Premium. The log shows the equivalent REST calls and the system notes that appear on the Issue.
Core commands
| Command | Purpose | Key parameters |
|---|---|---|
glab issue create | Create Issue | -t title,-d description,-l labels,-m milestone,-a assignee,-c confidential,--due-date,-w weight (Premium),-y |
glab issue list | List Issues | -l,-m,-a @me,--closed,--all |
glab issue view 1 --comments | View details and comments | -w Open in browser |
glab issue note 1 -m "/label ~x" | Comment (may include quick actions) | Quick actions also work in comments |
glab issue update 1 | Edit | --label,--unlabel,--milestone |
glab label list / create | project labels | can also be used glab api projects/:id/labels |
glab api projects/:id/milestones -X POST | Create milestone | -f title= -f start_date= -f due_date= |
cd ~/gitlablab/myapp # glab infers the project from the git remote
# Labels (on Free, :: is just an ordinary label)
for L in "type::feature:#1d63ed" "type::bug:#d9534f" "type::docs:#6c757d" \
"workflow::doing:#f0ad4e" "workflow::review:#5cb85c" "priority::high:#b42318"; do
NAME=${L%:*}; COLOR=${L##*:}
glab api projects/:id/labels -X POST -f name="$NAME" -f color="$COLOR" >/dev/null && echo "label $NAME"
done
# Milestone
glab api projects/:id/milestones -X POST -f title=v1.0 \
-f start_date=$(date +%F) -f due_date=$(date -d '+14 days' +%F) | python3 -c 'import sys,json;m=json.load(sys.stdin);print(m["iid"], m["title"], m["due_date"])'
label type::feature label type::bug label type::docs label workflow::doing label workflow::review label priority::high 1 v1.0 2026-11-30
glab issue create -t "Add /healthz endpoint" \ -d "Kubernetes / load balancers need a health check endpoint that does not depend on Redis, returning 200 and ok." \ -l "type::feature" -m v1.0 -a @me -y glab issue list -m v1.0
Creating issue in mygroup-lab/myapp #1 Add /healthz endpoint (about 1 second ago) https://gitlab.com/mygroup-lab/myapp/-/issues/1 Showing 1 open issue in mygroup-lab/myapp that match your search. #1 mygroup-lab/myapp#1 Add /healthz endpoint (type::feature) about 5 seconds ago
How to verify:glab issue view 1 Shows labels and milestones. Common errors:-a @me In some versions the username must be given; glab reports an error if the milestone name does not exist. Production use: Use scripts to create release checklist Issues in bulk; use --label to filter build reports.
Direct REST call: add or remove labels with quick-action parameters (equivalent to dragging on the board)
glab api projects/:id/issues/1 -X PUT -f add_labels="workflow::doing" glab api projects/:id/issues/1 -X PUT -f remove_labels="workflow::doing" -f add_labels="workflow::review"
Lab 3: Set up the planning system for myapp (about 6 minutes)
glab label list shows 6 labels.glab issue create -t "Add /healthz endpoint" -d "Returns 200 and ok, does not depend on Redis." -l "type::feature" -m v1.0 -y glab issue create -t "Add CI pipeline (pytest + docker build)" -d "Completed in Lesson 2." -l "type::feature" -m v1.0 -y glab issue create -t "Write operations runbook in wiki" -d "Completed in Module 7." -l "type::docs" -y glab issue list
#3 mygroup-lab/myapp#3 Write operations runbook in wiki (type::docs) #2 mygroup-lab/myapp#2 Add CI pipeline (pytest + docker build) (type::feature) #1 mygroup-lab/myapp#1 Add /healthz endpoint (type::feature)
If your Issue numbers are not 1, 2, 3 (for example, because you tested earlier), replace them with the actual numbers in the following commands.
glab issue note 1 -m '/label ~"workflow::doing" /estimate 1h Start implementing /healthz.' glab issue view 1 | head -20
After a quick action in a comment runs, it is removed, leaving only the text and a system note (for example, “added workflow::doing label”).
workflow::doing,workflow::review two columns. Confirm #1 appears in the doing column, and #2 and #3 are in the Open column. Drag #3 to doing and back to Open, then check #3’s activity: you will see two system notes about label changes.-c to create confidential Issues; regular Issues are visible to all project members.Case 1: Board columns do not match the real status
Problem: The same Issue appears in both the “doing” and “review” columns. Solution: The cause is that on the Free tier, using /label added a new workflow label without removing the old one. Instead, drag on the board (which automatically removes the source label), or write /unlabel ~"workflow::doing" /label ~"workflow::review" in a quick action; after upgrading to Premium, use scoped labels for automatic mutual exclusion. Limitation: Scoped mutual exclusion only applies on Premium / Ultimate.
Case 2: Release tracking across 12 microservices
Problem: A release involves multiple projects, and the PM cannot see the completion status at a glance. Solution: Create a group milestone 2026.12 in the top-level group; all related Issues and MRs from every project link to it, and the group milestone page automatically summarizes progress and burndown. Premium users can additionally use Epics to express feature themes and roadmaps to show the timeline. Limitation: A group milestone can only be used by projects in that group and its subgroups.
Case 3: Security defects should not be discussed publicly
Problem: Vulnerabilities reported in an open-source project are visible to everyone. Solution: Use confidential Issues (/confidential), visible only to Planner / Reporter and higher members, the author and assignees; the fix MR is completed in a private fork or security repository. Limitation: If an MR referenced in a confidential Issue remains visible in a public project, it must be handled separately.
Common errors and fixes
{"message":{"title":["has already been taken"]}} (creating a label or milestone)
Cause: A label with the same name already exists in this project or in an ancestor group (projects can see group labels).
glab api "projects/:id/labels?include_ancestor_groups=true&search=workflow"
Fix: Reuse the existing label, or rename it.
MR merged, but Issue #1 did not close automatically
Cause:① the keyword was misspelled (for example Close: #1,Related #1); ② the MR was merged into a branch that is not the default branch; ③ the project turned off “Auto-close referenced issues on default branch”; ④ the first push of an existing repository does not trigger closing.
glab mr view 1 | grep -i -E 'closes|fixes|resolves|implements'
glab api projects/:id | python3 -c 'import sys,json;p=json.load(sys.stdin);print(p["default_branch"], p.get("autoclose_referenced_issues"))'
Fix: Use Closes #1 and similar standard keywords; confirm the target branch; enable automatic closing under Settings → Repository → Branch defaults.
Quick action /weight 3 or /epic &1 had no effect and stayed in the comment as plain text
Cause: These quick actions require Premium; or your role is insufficient (for example, Guests cannot set milestones).
Fix: Check your tier and role; on the Free tier, use labels instead of weights, and a parent Issue instead of an Epic.
A newly created Issue does not appear on the board
Cause: The board has a filter (a Premium configurable board limited by milestone / label), or the Issue carries a column label while you are looking in the Open column.
Fix: Clear the filter at the top of the board; check the Issue’s labels; check the board’s “Edit board” settings.
1. Create a confidential bug Issue, add the type::bug and priority::high labels, and link it to milestone v1.0.
glab issue create -t "Redis password leaked in logs" -d "See attachment for details" -l "type::bug,priority::high" -m v1.0 -c -y
2. Use the REST API to move Issue #1 from doing to review (equivalent to dragging on the board).
glab api projects/:id/issues/1 -X PUT -f remove_labels="workflow::doing" -f add_labels="workflow::review"
A team uses GitLab.com Free and wants “multiple Issues under one theme with overall progress visible”, and also wants workflow labels to be mutually exclusive. Give a zero-cost solution and a solution after upgrading.
Zero cost: use a parent Issue (label type::epic) + Tasks / linked Issues to represent the theme, and use milestones to summarize progress; move workflow states only by dragging on the board (which automatically removes the source label), and in team conventions forbid adding workflow labels directly, or have a scheduled script check for “one Issue with two workflow labels”. After upgrading to Premium: use group Epics and roadmaps, and scoped labels for workflow:: automatic mutual exclusion, configurable boards and iterations.
Verified instructional videos
Official documentation
Video storyboard (about 75 seconds)
This course material cannot generate video or MP3 directly; the storyboard and narration script are provided.
Visual: an Epic card expands into three Issues, one of which expands further into two Tasks.
Narration: An Epic manages a theme, an Issue is deliverable work, and a Task breaks an Issue into small steps.
Visual: on the board, a card is dragged from doing to review; its label changes color from yellow to green, and an API call pops up beside it.
Narration: A board has no status of its own. Dragging a card means removing the old label and adding the new one.
Visual: Closes #1 in the MR description is highlighted; after the MR is merged, the Issue card slides into the Closed column and the milestone progress bar increases.
Narration: After the MR is merged into the default branch, Issues with a closing keyword close automatically, and milestone progress updates accordingly.
Module 4 · Merge Request end to end: review, approval and merge methods
- Create an MR in three ways (Web,
glab mr create,git push -o merge_request.create), and use Draft, reviewers and closing keywords correctly. - Complete a review: inline comments, resolving threads, suggested changes, submitting a review, approval.
- Read merge checks and API fields
detailed_merge_status, and understand when auto-merge merges and when it is canceled. - Choose Merge commit / Merge commit with semi-linear history / Fast-forward, along with the squash strategy, according to team needs.
What: what a Merge Request is
An MR is a request + discussion + checks collection for “merging a source branch into a target branch”. It stores: diff versions (each push produces a diff version, so you can compare changes between versions), comment threads, reviewers and approvals, linked pipelines, merge check results, and the system record after merging. The MR reference is written as !1; check it out locally with glab mr checkout 1, or fetch the server-side ref refs/merge-requests/1/head (deleted 14 days after the MR is closed or merged).
Why: why all changes should go through MRs
- Quality: a second pair of eyes + automated pipelines (Lesson 2).
- Compliance and audit: a permanent record of who approved which change and when; combined with protected branches (Module 6), direct pushes to
mainare forbidden. - Traceability: Issue → MR → commit → pipeline → deployment → environment, one chain.
How: the MR lifecycle
- Create: from the Issue page, “Create merge request” (automatically creates a branch and writes
Closes #1),glab mr create, or push with push options. You can first mark it as Draft (/draft), and a Draft cannot be merged. - Prepare (asynchronous): Sidekiq creates the diff, creates the pipeline, checks mergeability, links LFS objects and sends notifications; after that the API field
prepared_atgets a value. - Review: assign reviewers (who receive
review_requestednotifications and to-dos). Reviewers can turn on pending review, submit multiple comments at once, and choose Comment / Approve / Request changes. Suggestion (```suggestion code block) can be applied by the author with one click as a new commit. - Approval: on the Free tier, any Developer or higher member can approve, but approval is optional and does not block merging; Premium / Ultimate can set the number of required approvals, multiple approval rules, Code Owner approval, and approval settings such as “prevent author approval (on by default)” and “remove all approvals on new commits (default)”.
- Merge checks: Draft status, conflicts, unresolved threads, pipeline not successful, insufficient approvals, blocked by another MR, requested changes, and so on; if any one is unmet, merging is blocked.
- Merge: merge using the project’s merge method, optionally squashing and deleting the source branch; or set auto-merge (formerly “merge when pipeline succeeds”), which merges automatically once all checks pass.
- After merging: pushing to the target branch triggers post-receive → closes Issues with keywords (default branch only), deletes the source branch, triggers the target branch pipeline, and notifies participants.
How: the three merge methods and squash
| Merge method (Settings → Merge requests → Merge method) | Result | Requirement |
|---|---|---|
| Merge commit (default) | Every merge creates a merge commit (even when squashed) | No conflicts needed |
| Merge commit with semi-linear history | Still creates a merge commit, but merging is only allowed if the source branch can fast-forward → “semi-linear” history, where each feature is a small bubble | The source branch must be based on the latest commit of the target branch; otherwise rebase first |
| Fast-forward merge | No merge commit; the target branch moves forward directly, with fully linear history | Same as above; rebase first |
Squash option (Settings → Merge requests → Squash commits when merging):Do not allow(never squash),Allow(default off, can be checked),Encourage(default checked, can be unchecked),Require(always squash).
How: auto-merge rules (available on Free)
- After clicking Set to auto-merge , merging happens automatically once all merge checks are satisfied; if a retried pipeline succeeds after a failure, it also merges.
- If the source branch has new commits, auto-merge is canceled (new code needs review again).
- When using semi-linear or fast-forward,new commits on the target branch also cancel auto-merge (unless related settings such as rebasing before merge are enabled).
- Push options
merge_request.merge_when_pipeline_succeedsDeprecated since 17.11; usemerge_request.auto_merge.
When: how to choose a merge strategy
| Team characteristics | Recommended |
|---|---|
Want git log --first-parent main “one line per MR” | Merge commit + Squash: Encourage |
Need a linear history, convenient git bisect | Fast-forward + Squash: Require (use with a merge train when there are many MRs, Premium) |
| Want both a linear history and to keep “merge points” | Merge commit with semi-linear history |
Comparison with similar platforms
| GitLab MR | GitHub PR | Azure Repos PR | |
|---|---|---|---|
| Merge method | Choose one of three per project + squash policy | Repository allows several: merge / squash / rebase, chosen per MR | merge, squash, rebase, semi-linear; can be restricted by branch policy |
| Auto-merge | auto-merge | auto-merge | auto-complete |
| Required approvals | Premium | Free (public repos) / paid (private) | Branch policy, free |
| Merge queue | Merge trains (Premium) | Merge queue | No native support |
Commit graph: three merge outcomes for the same MR
State diagram: common values of detailed_merge_status
detailed_merge_status, not the deprecated merge_statusCore animation: the platform event flow of one MR from push to merge
First set the scenario (who merges, whether there is a pipeline, approval requirements, merge method), then “Play” or “Next”. Each step highlights the working component and shows the real API, Sidekiq job or Gitaly RPC name in the log. If any merge check is unmet, the flow stops at “Merge checks” and gives detailed_merge_status.
Tip: try “bob (Developer) + default protection settings”; it fails at the protected-branch check. Then try “Fast-forward + main has moved forward”; it gets need_rebase.
Core commands
| Command | Purpose | Key parameters |
|---|---|---|
glab mr create | Create MR | -t -d -b main --draft --reviewer -l -m -i (related Issue) --remove-source-branch --squash-before-merge --auto-merge --fill -y |
git push -o merge_request.create … | Create MR on push | .target= .title= .description= .label= .draft .auto_merge .remove_source_branch |
glab mr list / view / diff | View | --reviewer=@me,--draft,view --comments |
glab mr checkout 1 | Check out MR branch locally | Run tests locally during review |
glab mr note 1 -m | Comment (may include quick actions) | /approve /draft /ready /rebase /assign_reviewer @x |
glab mr approve 1 / revoke | Approve / revoke approval | On the Free tier approval is optional |
glab mr rebase 1 | Server-side rebase | semi-linear / FF requires it |
glab mr merge 1 | Merge or set auto-merge | --auto-merge (default true) -s squash -d Delete source branch --sha -m --squash-message -y |
# Option 1: glab glab mr create -b main -t "Add /healthz endpoint" -d "Closes #1" \ -l "type::feature" -m v1.0 --remove-source-branch --squash-before-merge -y # Option 2: push options (no glab needed; suitable for scripts / IDEs) git push -o merge_request.create -o merge_request.target=main \ -o merge_request.title="Add /healthz endpoint" -o merge_request.description="Closes #1" \ -o merge_request.label="type::feature" -o merge_request.remove_source_branch \ origin feat/healthz
remote: remote: View merge request for feat/healthz: remote: https://gitlab.com/mygroup-lab/myapp/-/merge_requests/1 remote: To gitlab.com:mygroup-lab/myapp.git * [new branch] feat/healthz -> feat/healthz
Query mergeability status (essential for scripts)
glab api projects/:id/merge_requests/1 | python3 -c 'import sys,json;m=json.load(sys.stdin);print(m["state"], m["detailed_merge_status"], m["has_conflicts"], m["merge_when_pipeline_succeeds"])'
opened mergeable False False
How to verify:detailed_merge_status must be mergeable for the MR to merge; mergeability is computed asynchronously, so right after a push it may show checking or preparing; check again later. Common errors: When pushing from the default branch, you must give merge_request.target; ci.skip only skips branch pipelines, not MR pipelines. Production use: Bots use --sha before merging to ensure the commit being merged is the one that was reviewed.
Suggested change (suggestion) syntax
```suggestion:-0+0
return "ok", 200, {"Content-Type": "text/plain"}
```
When commenting on a line in the MR’s Changes page, insert the block above; the author clicks Apply suggestion to generate a new commit (this triggers rules such as “remove approvals on new commits”).
Lab 4: Deliver myapp’s /healthz via an MR (about 7 minutes)
glab api projects/:id -X PUT -f merge_method=merge -f squash_option=default_on \ -F remove_source_branch_after_merge=true -F only_allow_merge_if_all_discussions_are_resolved=true >/dev/null && echo ok
squash_option values: never / default_off / default_on / always; merge_method: merge / rebase_merge (semi-linear) / ff.
cd ~/gitlablab/myapp && git switch main && git pull
git switch -c feat/healthz
cat >> app.py <<'EOF'
@app.get("/healthz")
def healthz():
# Does not access Redis: only indicates the process itself is healthy (readiness checks are discussed in later lessons)
return "ok", 200, {"Content-Type": "text/plain"}
EOF
cat >> tests/test_app.py <<'EOF'
def test_healthz():
resp = app.test_client().get("/healthz")
assert resp.status_code == 200
assert resp.data == b"ok"
EOF
. .venv/bin/activate && REDIS_HOST=127.0.0.1 pytest -q
git commit -am "feat: add /healthz endpoint"
.. [100%] 2 passed in 1.08s
git push -u origin feat/healthz glab mr create -b main -t "Add /healthz endpoint" -d "Closes #1" -l "type::feature" -m v1.0 --draft -y glab issue note 1 -m '/label ~"workflow::review" /unlabel ~"workflow::doing"'
Open Issue #1; you will see the system note “mentioned in merge request !1”.
healthz function’s comment line add the comment “Change the comment to English?”. Because “all threads must be resolved” is enabled, check the status:
glab api projects/:id/merge_requests/1 | python3 -c 'import sys,json;print(json.load(sys.stdin)["detailed_merge_status"])'
draft_status
The Draft check is shown first. Run glab mr update 1 --ready (or comment /ready) and check again; you will see discussions_not_resolved. In the MR, click Resolve thread , after which it becomes mergeable.
glab mr approve 1 # Free: optional approval; on Premium, if “prevent author approval” is enabled, this is rejected glab mr merge 1 --squash --remove-source-branch -y git switch main && git pull && git log --oneline --graph -3 glab issue view 1 | head -5
✓ Approved merge request !1 ✓ Merged merge request !1 * 5c3e9a1 (HEAD -> main, origin/main) Merge branch 'feat/healthz' into 'main' |\ | * 8b7d2f0 feat: add /healthz endpoint |/ * 2a91c4e feat: initial myapp (Flask + Redis counter on port 5000) title: Add /healthz endpoint state: closed
With only one commit, the squashed commit has the same content as the original commit; the merge commit message “Merge branch … into 'main'” is the default template and can be customized in settings. Issue #1 because Closes #1 was closed automatically (Sidekiq runs asynchronously, so it may take a few seconds).
glab mr rebase N before merging. When done, change the merge method back to Merge commit(Lesson 2 uses this setting)./healthz, and the Lesson 2 pipeline and the Lesson 3/4 deployment health checks depend on it.Case 1: After approval, the author quietly pushed more commits
Problem: After approval, the author pushed unreviewed changes and then merged them themselves. Solution: Premium: approval setting “When commits are added → Remove all approvals” (the default) + “Prevent approval by merge request creator” (enabled by default); Free: protected branches allow only Maintainers to merge, and by convention the merger is not the author; for automated merging, use glab mr merge --sha <SHA at review time>. Limitation: On the Free tier, approvals are not enforced; you can only rely on process and permission constraints.
Case 2: Frequent merges keep leaving main “beaten to it” by others
Problem: With Fast-forward, every MR must be rebased before merging, and a 30-person team keeps blocking each other. Solution: Enable merged-results pipelines and Merge trains (Premium, introduced in Lesson 2), so GitLab runs pipelines in queue order on the results after all MRs ahead of them have merged; or switch to semi-linear + auto-merge. Limitation: A merge train requires Premium and reliable CI.
Case 3: MR too large to review
Problem: A single MR changed 3,000 lines, so the review became a formality. Solution: The team agrees that MRs should not exceed 400 lines; share early using Draft; split large features into multiple MRs (on Premium, use “Merge request dependencies” to enforce order); use glab mr list --reviewer=@me to manage the review queue. Limitation: The line-count rule has to be enforced through team agreement or a CI check (in Lesson 2 you can write a job that counts diff lines).
Common errors and fixes
Merge blocked: detailed_merge_status = need_rebase (Fast-forward / semi-linear)
Cause: The target branch has moved forward, so the source branch cannot fast-forward.
glab mr rebase 1 # server-side rebase; or locally: git fetch && git rebase origin/main && git push --force-with-lease
Fix: After rebasing, wait for the pipeline again; if there are conflicts, they can only be resolved locally.
Merge blocked: detailed_merge_status = conflict
Cause: The source and target branches changed the same place.
glab mr checkout 1 && git fetch origin && git merge origin/main # or rebase # After resolving conflicts git add -A && git commit && git push
Fix: Simple conflicts can be resolved online in the MR page’s “Resolve conflicts” (this creates a merge commit on the source branch).
{"message":"405 Method Not Allowed"} (PUT /merge_requests/1/merge)
Cause: The MR is currently not mergeable: it is a Draft, has conflicts, checks have not passed, or it is already merged or closed.
glab api projects/:id/merge_requests/1 | python3 -c 'import sys,json;m=json.load(sys.stdin);print(m["state"], m["draft"], m["detailed_merge_status"])'
Fix: Based on the detailed_merge_status value, fix the corresponding check, or switch to auto-merge to wait for the checks to pass.
{"message":"401 Unauthorized"} or "You don't have permission to merge" (Developer merging into main)
Cause:main is a protected branch, and “Allowed to merge” is set to Maintainers only by default.
Fix: Have a Maintainer merge it; or in the branch rule set Allowed to merge to “Developers + Maintainers” (Module 6), while keeping Allowed to push set to “No one”.
auto-merge is canceled automatically: “canceled the automatic merge”
Cause: The source branch has new commits; or the target branch moved forward under semi-linear / FF; or the pipeline failed.
Fix: After reviewing the new commits, set auto-merge again; consider a merge train (Premium).
1. Using one git push command to create a Draft MR targeting main with auto-merge enabled.
git push -o merge_request.create -o merge_request.target=main -o merge_request.draft -o merge_request.auto_merge origin HEAD
2. Merge only while the MR head commit is still 8b7d2f0 the expected SHA, and squash and delete the source branch.
glab mr merge 1 --sha 8b7d2f0... --squash --remove-source-branch -y # --sha needs the full SHA
A team on GitLab.com Free requires “at least one reviewer before merging, linear main history, and one commit per MR”. Which of these can be achieved, and which cannot? Give a plan.
Linear history and “one commit per MR” can be achieved: set Merge method to Fast-forward and Squash to Require. “At least one reviewer” cannot be enforced by the platform on Free (required approvals need Premium); alternative: on protected branches set Allowed to push = No one and Allowed to merge = Maintainers, have a non-author Maintainer do the merging, enable “all threads must be resolved”, and after Lesson 2 add “the pipeline must succeed”. If approval must be enforced, upgrade to Premium or use a trial.
Verified instructional videos
Official documentation
- Merge requests
- Merge methods
- Auto-merge
- Merge request approvals
- Merge requests API (Merge status)
- Push options
Video storyboard (about 100 seconds)
This course material cannot generate video or MP3 directly; the storyboard and narration script are provided.
Visual: a terminal runs git push, and GitLab returns an MR link; “mentioned in !1” appears on Issue #1.
Narration: push a branch, create an MR, and write Closes #1 in the description.
Visual: a reviewer adds a suggested change on a line; the author clicks Apply, a new commit is created, and the approval badge is cleared.
Narration: reviewers can propose changes directly. A new commit invalidates the old approvals in Premium projects.
Visual: the merge checklist turns green item by item: not a Draft, no conflicts, threads resolved, pipeline succeeded, approvals met.
Narration: once all merge checks pass, the state becomes mergeable and auto-merge triggers immediately.
Visual: three commit graphs appear in turn: merge commit, semi-linear, fast-forward; finally the Issue card slides into Closed.
Narration: the merge method determines the shape of the history. After merging into the default branch, the linked Issue closes automatically.
Module 5 · glab CLI and REST / GraphQL API
glab api is the all-purpose key between the two- Use fluently
glabthe repo / issue / mr / ci / api subcommands, and understand how it infers the project from the git remote. - Use REST v4 to handle authentication, project path encoding, pagination and rate-limit handling; use GraphQL to retrieve nested data in one request.
- Choose the right token type and minimum scope for automation, and know the prefix and validity rules for each token type.
What: three automation entry points
| glab | REST API v4 | GraphQL API | |
|---|---|---|---|
| Endpoint | Local CLI (calls REST/GraphQL) | https://gitlab.com/api/v4/… | https://gitlab.com/api/graphql (single endpoint, POST) |
| Authentication | glab auth login, tokens stored in the system keyring | PRIVATE-TOKEN: <token> or Authorization: Bearer <token> | Authorization: Bearer <token>; queries require read_api, mutations require api |
| Strengths | Interactive and friendly, automatically detects the current project,glab api supports placeholders and pagination | Most complete coverage, most documentation, easy to use with curl | Retrieves multiple levels of nested data in one request; the client selects the fields |
| Tools | glab --help | docs.gitlab.com/api | GraphiQL: https://gitlab.com/-/graphql-explorer |
Why: why you need to know the API
Bulk operations (adding the same protection rule to 50 projects), reports (open MRs per week and average review time), integration with other systems (ChatOps, ticketing systems), and the “readiness review scripts” in later lessons all depend on the API. glab covers about 80% of daily operations; for the rest, use glab api to fill the gaps, without having to manage curl tokens and encoding.
How: five key points of REST
- Project identifier: a numeric ID, or the full URL-encoded path (
mygroup-lab%2Fmyapp). In a project directory,glab apisupports placeholders:id,:fullpath,:branch,:group,:useretc., automatically filled in from the git remote. - Pagination: default
per_page=20, maximum 100; response headersx-next-page,Link(may be omitted when there are many resultsx-total); some endpoints support more efficient keyset pagination (pagination=keyset).glab api --paginateAutomatically paginates. - Methods and parameters: GET to query, POST to create, PUT to update, DELETE to delete.
glab apiIn the-Ffield syntax, values are converted by type (numbers, booleans, JSON,@file),-falways a string; when field parameters are present, POST is the default. - Status codes: 401 unauthenticated / invalid token; 403 no permission or insufficient scope (
insufficient_scope); 404 resource does not exist or no permission to view it; 405 current state does not allow the action (e.g., MR not mergeable); 409 conflict; 422 parameter validation failed; 429 rate limited. - Rate limiting: GitLab.com currently limits authenticated API traffic to 2,000 requests per user per minute and unauthenticated traffic to 500 requests per IP per minute; the official docs also list new per-plan limits (for example, Free: 5,000 requests per user per hour and a burst of 100 per minute), marked as “not yet in effect”. When in effect, the lower value applies. Exceeding the limit returns
429, with response headersRateLimit-*andRetry-After.
How: key points of GraphQL
- Select fields as needed; nested objects are retrieved in one go (MR → author → approvals → head pipeline).
- Limits: query complexity 250 for authenticated users and 200 for unauthenticated; query text at most 10,000 characters; request timeout 30 seconds; most connections return at most 100 nodes per page.
- Pagination uses the Relay style:
first/after+pageInfo { hasNextPage endCursor };glab api graphql --paginaterequires the query to declare$endCursor: String. - A field that is
nullusually means no access; an emptynodesmeans permission exists but there is no data.
How: token types
| Token | Prefix | Identity | Tier / notes |
|---|---|---|---|
| Personal access token (PAT) | glpat- | You | Free; if no expiration date is set, it defaults to 365 days, and the default maximum is 365 days |
| Fine-grained personal access token | glpat- | You, but permissions are limited to specific resources and actions | 18.10 Beta,19.2 GA, available on Free |
| Project / group access token | glpat- | Automatically created bot user (project_{id}_bot_…) | GitLab.com requires Premium / Ultimate Premium (trial: only 1 allowed); on Self-Managed, any license |
| Deploy token | gldt- | deployment-only | read-only repository / mirror / packages etc., Free |
| CI/CD job token | —(CI_JOB_TOKEN) | running job | Invalid once the job ends (Lesson 2) |
| Runner authentication token | glrt- | Runner | New registration workflow (Lesson 2) |
When: which one to choose
- Personal use in the terminal: glab + PAT (or OAuth web sign-in).
- Team-shared automation (bots, scheduled reports): project / group access tokens (which do not become invalid when an employee leaves), or fine-grained PATs bound to a service account.
- For CI jobs accessing GitLab internally, prefer
CI_JOB_TOKEN; for deployment to the cloud, use OIDC in Lessons 3/4id_tokens, which requires no long-lived keys. - When you need to fetch many related fields in one go: GraphQL; for simple write operations or scenarios with the most documentation examples: REST.
Comparison with similar platforms
| GitLab | GitHub | Azure DevOps | |
|---|---|---|---|
| CLI | glab | gh | az devops / az repos |
| API | REST v4 + GraphQL | REST + GraphQL v4 | REST (versioned api-version) |
| Universal call | glab api | gh api | az devops invoke / az rest |
Architecture diagram: how glab decides “which API to call on which project”
-R or GITLAB_HOST to specify the target explicitlyComparison chart: request counts for the same report, REST vs GraphQL
Simulator: REST vs GraphQL and rate-limit counting
Drag the number of open MRs, choose a method, and click “Run”. The simulator issues requests one by one and deducts from the bucket according to the current limit of “2,000 per minute” (GraphQL also computes the query complexity cap of 250). The log shows the real request lines and response headers.
Common glab commands
| Command | Purpose | Notes |
|---|---|---|
glab auth login / status | Sign in / check | --hostname self-managed instance; --stdin; --web --device |
glab repo create / clone / view | Project | glab repo clone mygroup-lab/myapp; view -w Open browser |
glab issue …,glab mr … | Issue / MR | see Modules 3 and 4 |
glab ci status / view / list | Pipelines (Lesson 2) | glab ci view View jobs interactively |
glab api | Call any REST / GraphQL endpoint | -X -F -f --paginate --output ndjson -i --placeholder |
glab config set -g editor vim | Configuration | Every configuration key has a corresponding environment variable |
# REST: pagination + NDJSON + filtering with jq (or python)
glab api projects/:id/merge_requests?state=all --paginate --output ndjson | \
python3 -c 'import sys,json
for l in sys.stdin:
m=json.loads(l); print(m["iid"], m["state"], m["title"])'
# View response headers (rate-limit related)
glab api -i user 2>&1 | grep -i -E '^(ratelimit|retry-after|x-next-page)'
1 merged Add /healthz endpoint RateLimit-Limit: 2000 RateLimit-Remaining: 1998 RateLimit-Reset: 1763300460
Whether the headers appear and their exact values depend on GitLab.com’s current configuration; when a script receives 429, it should read Retry-After before retrying —glab api itself does not retry automatically, and exits directly and reports the wait time.
# GraphQL: fetch MR, approvals and pipeline in one request
glab api graphql -f query='
query($path: ID!) {
project(fullPath: $path) {
mergeRequests(state: opened, first: 50) {
nodes { iid title author { username } approved
detailedMergeStatus headPipeline { status } }
}
}
}' -f path="$GL_PROJECT"
{"data":{"project":{"mergeRequests":{"nodes":[]}}}}
# curl version (CI or machines without glab)
curl -s --header "Authorization: Bearer $GITLAB_TOKEN" --header "Content-Type: application/json" \
--data '{"query":"query { currentUser { username } }"}' https://gitlab.com/api/graphql
{"data":{"currentUser":{"username":"alice"}}}
Lab 5: Open MR report (REST and GraphQL versions, about 6 minutes)
cd ~/gitlablab/myapp && git switch main && git pull
for n in 1 2; do
git switch -c "demo/report-$n"
echo "- demo $n" >> README.md && git commit -qam "docs: demo $n"
git push -q -o merge_request.create -o merge_request.target=main \
-o merge_request.title="Demo report $n" $( [ $n = 2 ] && echo "-o merge_request.draft" ) origin "demo/report-$n"
git switch -q main
done
glab mr list~/gitlablab/mr_report_rest.sh):
#!/usr/bin/env bash
set -euo pipefail
P="${1:-$GL_PROJECT}"; PE=$(printf %s "$P" | sed 's#/#%2F#g')
glab api "projects/$PE/merge_requests?state=opened" --paginate --output ndjson |
while read -r line; do
iid=$(echo "$line" | python3 -c 'import sys,json;print(json.load(sys.stdin)["iid"])')
appr=$(glab api "projects/$PE/merge_requests/$iid/approvals" | python3 -c 'import sys,json;a=json.load(sys.stdin);print(len(a.get("approved_by",[])))')
echo "$line" | APPR="$appr" python3 -c 'import sys,json,os
m=json.load(sys.stdin)
print("!%-4s %-26s approvals=%s %s" % (m["iid"], m["detailed_merge_status"], os.environ["APPR"], m["title"]))'
done
bash ~/gitlablab/mr_report_rest.sh
!3 draft_status approvals=0 Draft: Demo report 2 !2 mergeable approvals=0 Demo report 1
glab api graphql -f path="$GL_PROJECT" -f query='
query($path: ID!) { project(fullPath: $path) { mergeRequests(state: opened, first: 100) {
nodes { iid title detailedMergeStatus approvedBy { nodes { username } } } } } }' |
python3 -c 'import sys,json
for m in json.load(sys.stdin)["data"]["project"]["mergeRequests"]["nodes"]:
print("!%-4s %-26s approvals=%d %s" % (m["iid"], m["detailedMergeStatus"], len(m["approvedBy"]["nodes"]), m["title"]))'
!3 DRAFT_STATUS approvals=0 Draft: Demo report 2 !2 MERGEABLE approvals=0 Demo report 1
Comparison: REST used 1 + N requests, GraphQL only used 1. You can use GLAB_DEBUG_HTTP=1 as a prefix to run the command and see every HTTP request in stderr.
for b in demo/report-1 demo/report-2; do iid=$(glab mr list --source-branch "$b" -F json 2>/dev/null | python3 -c 'import sys,json;d=json.load(sys.stdin);print(d[0]["iid"] if d else "")' || true) [ -n "$iid" ] && glab mr close "$iid" git push -q origin --delete "$b"; git branch -D "$b" done
If your glab version does not support -F json, close the MRs directly on the web, or use glab mr close <number>.
api scope (create MR) and a Developer or higher role; risk: a report script running on a large group with --paginate generates a large number of requests; watch rate limits and add backoff to scheduled jobs.Case 1: Overnight report script hit by 429 rate limiting
Problem: Iterating over 400 projects with 1 + N REST requests each; the overnight job returned many 429 Too Many Requests responses. Solution: Switch to a GraphQL query by group (group(fullPath:) { mergeRequests(...) }); for the remaining REST calls, read Retry-After the Retry-After header, use exponential backoff; use keyset pagination. Limitation: GraphQL complexity cap is 250; deeply nested queries must be split into multiple queries.
Case 2: An employee leaves and all release bots stop working
Problem: The bots used the departed employee’s PAT; after the account was disabled, all API calls returned 401. Solution: Migrate to group access tokens (Premium; bot users do not occupy a seat) or fine-grained PATs (service account), set a 90-day expiration and rotate them with a secrets management system; on Self-Managed, combine with expiration reminder emails. Limitation: On GitLab.com Free, project / group access tokens cannot be used; only a dedicated service account’s PAT or a fine-grained PAT.
Case 3: Use the API to unify merge settings across 80 projects
Problem: Merge methods, squash and thread checks are inconsistent across projects. Solution: A script iterates over groups/:id/projects?include_subgroups=true, and for each project PUT /projects/:id sets merge_method,squash_option,only_allow_merge_if_all_discussions_are_resolved; first --dry-run print the differences. Limitation: Changing project settings requires Maintainer; Premium group-level settings (such as group protected branches) can reduce per-project configuration.
Common errors and fixes
{"error":"insufficient_scope","error_description":"The request requires higher privileges than provided by the access token."}
Cause: The token scope is insufficient (for example, read_api a read-only token performing write operations).
glab api personal_access_tokens/self | python3 -c 'import sys,json;t=json.load(sys.stdin);print(t["name"], t["scopes"], t["expires_at"])'
Fix: Create a new token with the required scope (scopes cannot be modified after creation).
{"message":"404 Project Not Found"} (the path is correct)
Cause: The / in the path is not URL-encoded; or the token’s user has no permission to access the private project.
glab api "projects/mygroup-lab%2Fmyapp" | head -c 120
Fix: Use %2F or the numeric ID; confirm membership.
429 Too Many Requests / Retry later
Cause: The rate limit was exceeded.
glab api -i user 2>&1 | grep -i -E 'ratelimit|retry-after'
Fix: Wait according to Retry-After the value; reduce the number of requests (GraphQL, caching, incremental queries updated_after=)
GraphQL: "Query has complexity of 312, which exceeds max complexity of 250"
Cause: Nesting and pagination are too large.
Fix: Reduce first, remove unneeded nested fields, or split into multiple queries.
glab: none of the git remotes configured for this repository point to a known GitLab host
Cause: The current directory is not a GitLab repository, or the remote points to a host that you are not signed in to.
git remote -v; glab auth status
Fix: Go to the project directory, or use -R mygroup-lab/myapp; for a self-managed instance, run glab auth login --hostname gitlab.example.com.
1. Use glab api to list mygroup-lab the full paths of all projects under the group (including subgroups).
glab api "groups/mygroup-lab/projects?include_subgroups=true" --paginate --output ndjson | python3 -c 'import sys,json;[print(json.loads(l)["path_with_namespace"]) for l in sys.stdin]'
2. Use GraphQL to query the current username.
glab api graphql -f query='query { currentUser { username } }'You need to write a bot that runs every 15 minutes: it reads all open MRs in a group and automatically adds a comment to any MR that has had no reviewer for more than 3 days. How would you design the token, the API, and rate limiting?
Token: on Premium, use a group access token (Reporter is enough to read; commenting needs at least the matching Guest/Reporter permission; scope api), on Free use a fine-grained PAT of a dedicated service account, limited to that group and the comment action, with expiration and rotation. API: use GraphQL to query open MRs by group, using the createdAt,reviewers, fetching them in one paginated pass; post comments with REST POST /projects/:id/merge_requests/:iid/notes. Rate limiting: use incremental queries, handle 429 with Retry-After, and add an idempotency marker to comments (check first whether it has already been commented on).
Verified instructional videos
No verified introductory glab or GitLab GraphQL video was found; a storyboard script is provided. Note that “GitLab Duo CLI” is a different product, not glab.
Official documentation
- GitLab CLI (glab)
- glab api
- REST API
- GraphQL API
- GitLab.com rate limits
- Personal access tokens
- Fine-grained personal access tokens
Video storyboard (about 80 seconds)
This course material cannot generate video or MP3 directly; the storyboard and narration script are provided.
Visual: in the terminal, glab mr list, with the REST request line it sends overlaid transparently beside it.
Narration: glab infers the project from the git remote, then calls REST or GraphQL.
Visual: on the left, REST requests stack up one after another; on the right, GraphQL returns nested JSON in one response; the quota bar at the top drops quickly on the left.
Narration: the more nested the data, the fewer requests GraphQL needs; but it has a complexity cap of two hundred and fifty.
Visual: four token cards: glpat, project token bot, gldt, CI_JOB_TOKEN, with level and validity labeled beside each.
Narration: individuals use PATs, team bots use project or group tokens, and jobs use job tokens internally.
Module 6 · Protected branches, push rules and CODEOWNERS
- In Branch rules for
mainconfigure Allowed to merge / Allowed to push and merge / Allowed to force push, and protect release tags. - Explain how a single
git pushpush passes through the server-side checks in sequence, and the error text for each. - Write a CODEOWNERS file with sections, optional sections and multi-approval counts
CODEOWNERS, and understand how it links with protected branches and approval rules (Premium). - On the Free tier, replace push rules with process and CI.
What: three layers of protection
| Mechanism | What it protects | Where it is checked | Tier |
|---|---|---|---|
| Protected branches | Who can push, who can merge via MR, whether force pushes are allowed, whether deletion is allowed | Push: /internal/allowed access check; merge: at MR merge time | Free (group-level rules Premium) |
| Protected tags | Who can create / delete matching tags (release tags) | Push access check | Free |
| Push rules | Commit messages, branch names, author email, file name / size, secret files, signed commits, DCO | Push access check (per commit) | Premium / Ultimate |
| CODEOWNERS | Who must approve MRs that change certain paths; direct pushes to matching paths are rejected | MR approval rules + push check | Premium / Ultimate |
Why: why enforce on the server
Client-side hooks (pre-commit) can be --no-verify bypassed (for example with --no-verify); only server-side checks can guarantee that “every commit on a production branch goes through MR, review and the pipeline”. This is also the basis of Lesson 2’s “protected variables are exposed only to protected branches” and Lessons 3/4’s “only main gets cloud deployment permissions (the OIDC ref_protected claim) is the basis.
How: options for protected branches (Settings → Repository → Branch rules)
- Allowed to merge: who can merge into this branch via MR (also determines who can create the protected branch in the UI / API).
- Allowed to push and merge: who can push directly (and merge). Set to No one to mean “MR only”.
- Allowed to force push: a toggle; when enabled, people with push permission can force-push. Always turn this off for production branches.
- Require approval from code owners (Premium): changes matching CODEOWNERS must be approved by code owners, and direct pushes to matching paths are rejected.
- Wildcards:
release/*,*-stable; when multiple rules match,the most permissive one applies. - The default branch is protected when the project is created; group Owners can set the default-branch protection level for new projects. The legacy project-level “Protected branches” setting is being migrated to Branch rules page.
- API access level values:
0No access,30Developer,40Maintainer,60Admin.
How: push rules (Premium; Settings → Repository → Push rules)
| Category | Rule |
|---|---|
| User verification | Reject unverified users, reject inconsistent usernames, check whether the commit author is a GitLab user, commit author email regex |
| Commit message | require matching regex, reject matching regex |
| Branch name | Branch name regex |
| Prevent accidents | Reject unsigned commits, forbid using git push delete tags |
| Files | Block pushing secret files, forbidden file name regex, maximum file size |
| DCO | Reject commits without DCO sign-off (Signed-off-by) |
Push rules can be set at the group level as defaults for new projects. Self-Managed / Dedicated administrators can also configure server hooks; GitLab.com does not support custom server hooks.
How: key CODEOWNERS syntax points
- Location (the first one found in this order):
./CODEOWNERS→./docs/CODEOWNERS→./.gitlab/CODEOWNERS. - Within the same section,the last matching rule takes effect (place specific paths
*after the general ones). - Sections:
[Backend]; optional sections:^[Docs](does not block merging); requires 2 approvals:[Database][2](for protected branches only); section default owners:[Backend] @alice. - Owners:
@user,@group/subgroup,@@maintainer(by role, direct members only). Paths:/A leading slash anchors to the root directory,/a trailing slash denotes a directory,**/matches across levels,!exclude.
When: what to do on Free
main: Allowed to push = No one, Allowed to merge = Maintainers (or Developers + Maintainers), Force push off.- Commit message / branch name conventions: add check jobs in CI (Lesson 2), together with “the pipeline must succeed”; locally use pre-commit / commit-msg hooks as reminders.
- Large files and secrets: run secret detection in CI (the GitLab Secret Detection template is available on Free; Lesson 5).
- A CODEOWNERS file can be committed on Free (so it is ready for a later upgrade), but it does not create approval requirements.
Comparison with similar platforms
| GitLab | GitHub | Azure Repos | |
|---|---|---|---|
| Branch protection | Protected branches / Branch rules (Free) | Branch protection rules / Rulesets | Branch policies |
| Push content rules | Push rules (Premium) | Rulesets push rules (some paid) | Some approval policies and Git settings |
| Code owners | CODEOWNERS + sections + multiple approvals (Premium) | CODEOWNERS | Automatically included reviewers |
Flow diagram: order of server-side checks for one git push
Relationship diagram: CODEOWNERS, approval rules and protected branches
Server-side push check simulator
Choose the pusher, push method and content, then click “Push”. The simulator runs the checks in the order of Figure 6-1, stops at the first failure, and shows the error the git client would see. Push rules and CODEOWNERS take effect only when “Premium” is checked.
Core commands
| Command | Purpose | Notes |
|---|---|---|
glab api projects/:id/protected_branches | View / create protected branches | POST: name push_access_level merge_access_level allow_force_push code_owner_approval_required (Premium) |
… protected_branches/main -X PATCH | Modify | When changing access levels, “delete and recreate” is commonly used |
glab api projects/:id/protected_tags | Protected tags | name=* create_access_level=40 |
glab api projects/:id/push_rule | Push rules (Premium) | commit_message_regex branch_name_regex max_file_size prevent_secrets deny_delete_tag |
GIT_TRACE=1 git push | Debug pushes | View client and server interaction |
cd ~/gitlablab/myapp
glab api projects/:id/protected_branches | python3 -c 'import sys,json
for b in json.load(sys.stdin):
print(b["name"], "push:", [a["access_level_description"] for a in b["push_access_levels"]],
"merge:", [a["access_level_description"] for a in b["merge_access_levels"]], "force:", b["allow_force_push"])'
main push: ['Maintainers'] merge: ['Maintainers'] force: False
# Set to “merge only via MR”: delete first, then recreate with the new rules glab api projects/:id/protected_branches/main -X DELETE glab api projects/:id/protected_branches -X POST -f name=main \ -F push_access_level=0 -F merge_access_level=40 -F allow_force_push=false # Protect all tags: only Maintainers can create them glab api projects/:id/protected_tags -X POST -f name='*' -F create_access_level=40
{"id":9182736,"name":"main","push_access_levels":[{"access_level":0,"access_level_description":"No one",...}],"merge_access_levels":[{"access_level":40,"access_level_description":"Maintainers",...}],"allow_force_push":false,"code_owner_approval_required":false}
{"name":"*","create_access_levels":[{"access_level":40,"access_level_description":"Maintainers"}]}
How to verify: As a Maintainer, pushing directly git push origin main is also rejected (because push = No one). Common errors: Within the few seconds between deletion and recreation the branch is unprotected; in production, do this in a maintenance window, or use PATCH to modify a single access level item. Production use: Use a script to apply the same rule to all projects in the group; on Premium, group-level protected branches can be used directly.
Push rules (Premium or trial)
glab api projects/:id/push_rule -X POST \ -f commit_message_regex='^(feat|fix|docs|chore|refactor|test)(\(.+\))?: .+' \ -f branch_name_regex='^(main|(feat|fix|docs|chore)/[a-z0-9._-]+)$' \ -F max_file_size=50 -F prevent_secrets=true -F deny_delete_tag=true
When push rules already exist, use -X PUT. Calls on the Free tier return 404 or 403.
Lab 6: Allow changes to main only via MR, and prepare CODEOWNERS for later (about 6 minutes)
git switch main && git pull echo "direct push test" >> README.md && git commit -qam "docs: direct push test" git push origin main
remote: GitLab: You are not allowed to push code to protected branches on this project. To gitlab.com:mygroup-lab/myapp.git ! [remote rejected] main -> main (pre-receive hook declined) error: failed to push some refs to 'gitlab.com:mygroup-lab/myapp.git'
git reset --hard origin/main # undo local test commits
git commit --allow-empty -qm "chore: tmp" && git push --force origin HEAD:main; git reset -q --hard origin/main
Because push is already No one, you get the “not allowed to push” error here as well; if you set push to Maintainers and try again, you will see the “not allowed to force push” error.
git switch -c chore/codeowners
mkdir -p .gitlab
cat > .gitlab/CODEOWNERS <<EOF
# Default: project Maintainers
* @@maintainer
[App]
/app.py @${GL_USER}
/tests/ @${GL_USER}
[Infra]
/Dockerfile @${GL_USER}
/.gitlab-ci.yml @${GL_USER}
^[Docs]
*.md @${GL_USER}
EOF
git add .gitlab/CODEOWNERS && git commit -qm "chore: add CODEOWNERS"
git push -q -o merge_request.create -o merge_request.target=main \
-o merge_request.title="Add CODEOWNERS" -o merge_request.remove_source_branch origin chore/codeowners
glab mr merge chore/codeowners --squash -y || glab mr list
glab mr merge also accepts a branch name as an argument. After merging git switch main && git pull. On the web, open .gitlab/CODEOWNERS, and Premium projects show the syntax validation results.
Bad_Name and observe the rejection message. These settings stop working when the trial ends; Lessons 2–4 do not depend on them.Case 1: A wildcard rule accidentally opened main
Problem: Someone added a rule * (Allowed to push: Developers), and as a result Developers could push directly to main. Cause: When multiple rules match the same branch, the most permissive one applies. Solution: Delete the broad rule and replace it with exact rules such as release/*,main ; in the readiness review script (Module 8), detect * rules. Limitation: Group-level protected branches (Premium) can be pushed out uniformly, avoiding per-project configuration.
Case 2: A 2 GB database backup was pushed into the repository
Problem: A developer accidentally pushed dump.sql to a feature branch, which bloated the repository and slowed down clones. Solution: Premium: push rule max_file_size=50 + forbidden file name; Free: exclude it in \.(sql|bak|dump)$; Free: exclude it in .gitignore and check large files in CI. Large files that were already pushed need to be cleaned up with git filter-repo , then after cleaning up the history, upload the commit map under Settings → Repository → Repository cleanup and run the repository cleanup. Limitation: Push rules only check newly pushed commits and do not clean up history.
Case 3: Infrastructure code must be approved by the platform team
Problem: App developers changed the Dockerfile and CI configuration and merged them themselves, so the built images included debugging tools. Solution: A CODEOWNERS section [Infra][2] @mygroup-lab/platform, with Code Owner approval enabled for main; the approval setting “remove Code Owner approvals when new commits are added (if their files change)”. Limitation: Premium; a group referenced in CODEOWNERS must be invited to the project (or be a parent group) to count as a valid owner.
Common errors and fixes
remote: GitLab: You are not allowed to push code to protected branches on this project.
Cause: The target branch is protected, and your role is not in Allowed to push and merge (by default only Maintainers; when set to No one, nobody can).
glab api projects/:id/protected_branches/main | python3 -c 'import sys,json;b=json.load(sys.stdin);print([a["access_level_description"] for a in b["push_access_levels"]])'
Fix: Push to a feature branch and create an MR; if truly needed (such as the first initialization), a Maintainer temporarily adjusts the settings.
remote: GitLab: You are not allowed to force push code to a protected branch on this project.
Cause: A non-fast-forward push (pushing after a rebase,--force), while the branch does not have Allowed to force push enabled.
Fix: Do not rewrite the history of protected branches; if a feature branch was accidentally protected (by a wildcard rule), adjust the rule.
remote: GitLab: You are not allowed to create this tag as it is protected. (wording may differ slightly)
Cause: The tag matches a protected tag rule, and you are not in Allowed to create.
Fix: Have a Maintainer create the release tag, or create it through a CI release job (Lesson 2).
remote: GitLab: Commit message does not follow the pattern '^(feat|fix|docs|chore)…' (push rule)
Cause: In the push,any one commit’s message does not comply with the rule (including commits from long ago).
git log --format='%h %s' origin/main..HEAD git rebase -i origin/main # use reword to fix non-compliant commit messages (interactive; run it in your own terminal)
Fix: Rewrite the commit messages and push to a feature branch; configure a commit-msg hook locally to catch this earlier.
Pushes to protected branches that contain changes to files matching CODEOWNERS are not allowed (direct pushes after Code Owner approval is enabled)
Cause: main has “Require approval from code owners” enabled, and the push changes paths matched by CODEOWNERS (the exact error wording varies by version).
Fix: Merge via MR; or, if the change should not be controlled, adjust the CODEOWNERS paths (use ! to exclude it).
1. Use the API to protect release/*: Developers can merge, nobody can push directly, and force pushes are forbidden.
glab api projects/:id/protected_branches -X POST -f name='release/*' -F push_access_level=0 -F merge_access_level=30 -F allow_force_push=false
2. Write a CODEOWNERS snippet: /db/ The directory requires @mygroup-lab/dba approval from 2 people in the group, and docs/ is an optional section.
[Database][2] @mygroup-lab/dba /db/ ^[Docs] /docs/ @pm
A GitLab.com Free team wants: “commit messages must follow Conventional Commits, no direct pushes to main, and no files larger than 50 MB can be pushed”. Which of these can be configured with platform settings? How do you handle the rest?
“No direct pushes to main” can be done with Free protected branches (push = No one). Commit message rules and file size limits are push rules and need Premium. Free alternative: run check jobs in the MR pipeline (iterating over $CI_MERGE_REQUEST_DIFF_BASE_SHA..HEAD commit messages and file sizes; Lesson 2), and enable “the pipeline must succeed”; locally use a commit-msg hook as a reminder. The drawback is that non-compliant commits already exist in the feature branch; they just cannot be merged into main.
Verified instructional videos
Official documentation
Video storyboard (about 80 seconds)
This course material cannot generate video or MP3 directly; the storyboard and narration script are provided.
Visual: a git push data packet reaches the server and is stopped by a gate before “ref update”; four check lights turn on in turn on the gate.
Narration: all protections run on the server, before anything is written: role, protected branches, push rules, code owners.
Visual: the terminal shows “not allowed to push code to protected branches”, and then the developer pushes to a feature branch instead and creates an MR.
Narration: set main so that nobody can push directly; all changes must go through an MR.
Visual: the three sections of the CODEOWNERS file are highlighted in turn, and the MR approval panel shows the three corresponding rules, with Docs marked as optional.
Narration: CODEOWNERS decides who must approve based on the path; optional sections do not block merging.
Module 7 · Wiki, notifications, search and productivity
- Use the Wiki as an independent Git repository: web editing, cloning, custom sidebar
_sidebar. - Understand the notification-level inheritance chain (project → group → global) and
X-GitLab-NotificationReason, learn to reduce noise, and use the to-do list to handle items that need your action. - Distinguish basic search, advanced search and exact code search; use GFM references, shortcuts and description templates fluently.
What: Wiki
- Each project Wiki is a separate Git repository (separate from the code repository); it can be edited on the web, or cloned locally, edited, and pushed (the Wiki page’s Wiki actions → Clone repository gives the address).
- Supports Markdown, AsciiDoc, RDoc, Org; pages are stored as files (Markdown uses
.mdand similar extensions). - The default sidebar shows pages by hierarchy and alphabetical order; creating a page named
_sidebarcan completely replace the navigation. - The project Wiki is available on Free; group Wiki requires Premium. Planner, Developer and higher roles can edit the Wiki (Reporter cannot).
What: notifications and to-dos
| Notification level | Meaning |
|---|---|
| Global | Use the setting from the parent level (group / global) |
| Watch | Almost all activity |
| Participate | Items you are involved in (created, commented on, assigned, mentioned, etc.) |
| On mention | Only when you are @ |
| Disabled | Receive nothing |
| Custom | Participate + the events you choose (such as “pipeline failed” or “new MR”) |
Inheritance: project settings override the group, and the group overrides global. If a project or subgroup is set to Global, the first non-Global setting up the parent chain applies. Every notification email carries X-GitLab-NotificationReason headers (such as assigned,review_requested,mentioned,subscribed,own_activity), which you can use to write email filter rules. To-Do List (shortcut Shift+t) Only collects items that need your action: assigned, review requested, mentioned, pipeline failed, etc.
What: three types of search
| Type | Mechanism | Scope | Characteristics |
|---|---|---|---|
| Basic search: exact substring matching in the database / Gitaly | Exact substring matching in the database / Gitaly | Free | Code, commits, comments and Wiki can only be searched within a project; code cannot be searched at group or global scope. |
| Advanced search | Elasticsearch / OpenSearch index | Premium | Code search at group and global scope, with syntax filters |
| Exact code search | Zoekt index, supporting exact and regex modes | Premium | 15.9 Beta → 18.6 limited availability → 19.5 GA; enabled by default on GitLab.com paid subscriptions |
URL parameter search_type=basic|advanced|zoekt can force a search type; searching non-default branches falls back to basic search.
What: GitLab Flavored Markdown (GFM) references
| Syntax | Referenced object | Syntax | Referenced object |
|---|---|---|---|
@alice | User (sends a notification) | ~bug,~"workflow::review" | Label |
#123,group/project#123 | Issue (cross-project) | %v1.0,%"release candidate" | Milestone |
!123 | Merge Request | &123 | Epic |
$123 | Code snippet | 9ba12248,a...b | Commit / commit range |
[[Home]] | Wiki page | #123+ / #123+s | Display title / summary |
A reference is more than a link: the referenced object shows a system note (“mentioned in !1”), which is the source of traceability.
How: productivity tools
- Shortcuts:? keyboard shortcut list,s or / focus search,. open Web IDE,Shift+m my MRs,Shift+i my Issues,f focus the filter bar.
- Description templates:
.gitlab/issue_templates/*.md,.gitlab/merge_request_templates/*.md; a template whose file name isDefault.mdis automatically used as the default (available on Free; specifying a default template in project settings and group-level templates requires Premium). - Code snippets: personal or project-level code / configuration snippets, which are themselves Git repositories.
- Comment templates: save frequently used replies in personal settings.
When: when to use the Wiki and when to keep documents in the code repository
| Keep in the code repository (docs/, README) | Put in the Wiki |
|---|---|
| Documents that change with code versions and need MR review (API docs, architecture decision records ADR) | Operations manuals, on-call Runbooks, meeting notes, FAQs — need quick editing and do not need to be released with code |
Comparison with similar platforms
| GitLab | GitHub | Azure DevOps | |
|---|---|---|---|
| Wiki | Project Wiki (Git repository) + group Wiki (Premium) | Repository Wiki (Git repository) | Project Wiki or “code as wiki” |
| Code search | Basic / advanced / exact (Zoekt) | Code search (site-wide) | Code Search extension |
| Notifications | Inherited by project / group level + to-dos | Watch + Notifications inbox | Subscription rules |
Inheritance diagram: how the notification level is determined
Data flow: what a GFM reference triggers
GFM reference parser
Type a comment below (you can edit the example). The simulator recognizes the users, Issues, MRs, Epics, labels, milestones, snippets and Wiki links in it using GitLab’s reference syntax, and lists the actions GitLab would perform as a result. This is a simplified regex parser; real rendering also checks whether objects exist and the reader’s permissions.
Core commands
| Command | Purpose | Notes |
|---|---|---|
glab api projects/:id/wikis -X POST | Create Wiki page | -f title= -f content=@file -f format=markdown (-F content=@file read from file) |
glab api projects/:id/wikis?with_content=1 | List pages | slug used for updates: PUT …/wikis/:slug |
git clone git@gitlab.com:GROUP/PROJECT.wiki.git | Clone the Wiki repository | use the address shown under Clone repository on the page |
glab api projects/:id/notification_settings -X PUT | Set the project notification level | -f level=participating|watch|global|mention|disabled|custom |
glab api projects/:id/search | Search within the project | scope=blobs|commits|issues|merge_requests|notes|wiki_blobs|milestones search= |
glab api todos | To-do list | POST todos/:id/mark_as_done |
cd ~/gitlablab/myapp glab api "projects/:id/search?scope=blobs&search=healthz" | python3 -c 'import sys,json for r in json.load(sys.stdin): print(r["path"], r["startline"], r["data"].strip().splitlines()[0])'
app.py 21 @app.get("/healthz")
tests/test_app.py 12 def test_healthz():
glab api projects/:id/notification_settings -X PUT -f level=participating glab api notification_settings | python3 -c 'import sys,json;print(json.load(sys.stdin))'
{"level":"participating"}
{'level': 'participating', 'notification_email': 'alice@example.com'}
How to verify: The bell icon in the upper-right corner of the project page shows the current level. Common errors: The search API’s scope=blobs on Free can only be used with project-level endpoints; group-level blobs searches require advanced or exact code search. Production use: Use the search API to find in bulk projects that still use deprecated images or hard-coded addresses (group-level search on Premium).
Lab 7: Runbook Wiki, MR template and notifications (about 7 minutes)
cat > /tmp/runbook.md <<'EOF' # myapp Runbook | Item | Value | |------|----| | Port | 5000 | | Health check | `GET /healthz` → `200 ok` | | Dependency | Redis (`REDIS_HOST`, default `redis`) | | Code | !1 introduced /healthz, see #1 | ## Local run ```bash docker run -d --name redis redis:7 docker build -t myapp:dev . && docker run --rm -p 5000:5000 --link redis myapp:dev curl -s localhost:5000/healthz ``` ## Common failures - `/` returns `"hits": null`: Redis is unreachable; check `REDIS_HOST`. EOF glab api projects/:id/wikis -X POST -f title=Runbook -F content=@/tmp/runbook.md -f format=markdown | python3 -c 'import sys,json;w=json.load(sys.stdin);print(w["slug"], w["title"])' glab issue close 3 && glab issue note 3 -m "Runbook completed: [[Runbook]]"
Runbook Runbook ✓ Closed issue #3
The --link in the local run section is for demonstration only; Lesson 2 will run Redis using Compose / CI services. redis:7 For the tag, follow the version used in the Docker course.
git@gitlab.com:mygroup-lab/myapp.wiki.git), edit locally, Runbook.md and then push git push; the web updates immediately.git switch main && git pull && git switch -c docs/mr-template mkdir -p .gitlab/merge_request_templates cat > .gitlab/merge_request_templates/Default.md <<'EOF' ## Changes ## Related Issue Closes # ## Verification - [ ] Local `pytest` passes - [ ] Runbook updated (if operations are affected) /label ~"workflow::review" EOF git add .gitlab && git commit -qm "docs: add default MR template" git push -q -o merge_request.create -o merge_request.target=main -o merge_request.title="Add MR template" \ -o merge_request.remove_source_branch origin docs/mr-template glab mr merge docs/mr-template --squash -y && git switch main && git pull -q
Quick actions at the end of the template run when the MR is created. Afterward, when you create a new MR on the web, the description is automatically filled with this template.
glab api projects/:id/notification_settings -X PUT -f level=custom -F failed_pipeline=true -F new_merge_request=true
glab api todos | python3 -c 'import sys,json;[print(t["action_name"], t["target_type"], t["target"].get("title","")) for t in json.load(sys.stdin)]'
Custom level = Participate + the events you choose; you will receive an email when the Lesson 2 pipeline fails.
Case 1: The on-call engineer receives 600 GitLab emails a day
Problem: The global setting is Watch, so every comment on every project sends an email, and real alerts get buried. Solution: Change the global setting to Participate; set key projects to Custom (adding only “pipeline failed”); in the email client, sort by X-GitLab-NotificationReason into folders; start each day from the to-do list. Limitation: Notification settings belong to each user; the team can only recommend a configuration.
Case 2: Find all projects still using python:3.9 images
Problem: The security team needs to locate old base images across 300 projects. Solution: On Premium, use exact code search (Zoekt) to search across the top-level group for FROM python:3.9; on Free you can only call projects/:id/search?scope=blobs for each project. Limitation: Only the indexed content of the default branch is searched.
Case 3: The Runbook was kept in personal notes, and could not be found during an incident
Problem: During an overnight incident, the on-call person could not find the steps for handling a Redis failure. Solution: Each service’s Wiki has a unified Runbook page,_sidebar a fixed entry point; alert messages link directly to the Wiki page; the incident review Issue uses [[Runbook]] references and updates it. Limitation: A unified group-level Wiki requires Premium; on Free you can use a dedicated runbooks project’s Wiki instead.
Common errors and fixes
{"message":"403 Forbidden"} (POST /projects/:id/wikis)
Cause: The role is insufficient (Reporter cannot edit the Wiki), or the project has the Wiki feature turned off.
glab api projects/:id | python3 -c 'import sys,json;p=json.load(sys.stdin);print(p.get("wiki_access_level"))'
Fix: Use Planner / Developer or higher; enable the Wiki under Settings → General → Visibility, project features.
Not receiving any GitLab notification emails
Cause: The notification level is Disabled / On mention; the notification email is not verified; email is being filtered; or the action was yours (by default you are not notified of your own activity).
glab api notification_settings glab api projects/:id/notification_settings
Fix: Adjust the level; check the notification email under Edit profile → Notifications; turn on “receive notifications for my own activity” if needed.
Searching code shows that search is only possible within a project / there are no “Code” results at group scope
Cause: The Free tier has only basic search; code search is not supported at group or global scope.
Fix: Go into a specific project to search; or use Premium’s advanced / exact code search.
Reference #12 shows as plain text and does not become a link
Cause: The object does not exist, the reader has no permission to view it (a cross-project reference to a private project), or it is written inside a code block / inline code.
Fix: Check the number and project path (cross-project references must be written as group/project#12); check permissions.
1. Search myapp for all lines that mention REDIS_HOST .
glab api "projects/:id/search?scope=blobs&search=REDIS_HOST"
2. Set myapp’s notification level to “only when mentioned”.
glab api projects/:id/notification_settings -X PUT -f level=mention
The team wants architecture decision records (ADRs) to be reviewed and saved with the versions, and on-call Runbooks to be quickly editable during incidents. Where should each go? How should they link to each other?
ADRs go in a directory of the code repository, docs/adr/, reviewed through MRs (CODEOWNERS can name the architects, Premium), and released with code versions. Runbooks go in the project Wiki, where the on-call person edits them directly during an incident (Wiki history is traceable). In the ADR, link to the Runbook with a full URL or [[Runbook]] (the same project’s Wiki); in the Runbook, link to the ADR file with a permanent link (by commit SHA).
Verified instructional videos
No oEmbed-verified video specifically on the GitLab Wiki, notifications or search was found. You can refer to the official “Setting up your Organization” series in Module 3 (Plan and Track Work). A storyboard script is provided below.
Official documentation
- Wiki
- Notification emails
- Search · Exact code search
- GitLab Flavored Markdown
- Keyboard shortcuts
- Description templates
Video storyboard (about 75 seconds)
This course material cannot generate video or MP3 directly; the storyboard and narration script are provided.
Visual: a second repository icon, myapp.wiki.git, appears beside the project repository; web edits and local git pushes both write to it.
Narration: The Wiki is a separate Git repository, suitable for documents like Runbooks that need quick edits.
Visual: the bell icon passes settings between the global, group and project levels; the inbox count drops from 600 to 20.
Narration: notification levels are inherited from project to group to global. Participate plus the to-do list is recommended.
Visual: the @, #, !, ~ and % characters in a comment are highlighted in turn and become links; the referenced Issue shows a “mentioned in” note.
Narration: GitLab references are more than links; they also leave a record on the referenced object and notify the people mentioned.
Module 8 · Collaboration readiness review and troubleshooting basics
- Use 12 checks to assess whether a project is “ready for multi-person collaboration”, and run the review automatically with a glab api script.
- Locate GitLab collaboration errors with a five-layer model: “authentication → authorization (roles) → protection rules → tier → state”.
- Use fluently
GIT_TRACE,glab api -i,GLAB_DEBUG_HTTP,detailed_merge_statusand other diagnostic tools.
What: collaboration readiness review
Before the team starts committing code to a project and before CI/CD is connected in Lesson 2, confirm that the baseline configuration in four areas (people, permissions, process, knowledge) is in place. It is the platform-level equivalent of a pre-launch check, and its results should be able to be automated and run repeatedly (after a new project is created and at each quarterly access review).
Why: why this is done at the end of Hour 1
From Lesson 2 onward, protected branches decide which pipelines can access protected variables; in Lessons 3/4, the claims in OIDC tokens ref_protected (such as the ones listed) decide which jobs can deploy to the cloud. If main is not properly protected, all later security controls lose their foundation.
How: 12 checks
| # | Category | Check item | How to check | Module |
|---|---|---|---|---|
| 1 | People | Top-level group enforces 2FA | groups/:id → require_two_factor_authentication | 2 |
| 2 | People | No more than 3 Maintainers or higher; external members have an expiration date | projects/:id/members/all | 2 |
| 3 | People | Project is Private | projects/:id → visibility | 1, 2 |
| 4 | Process | Default branch is main and protected | default_branch,protected_branches/main | 6 |
| 5 | Process | main forbids direct pushes and force pushes | push_access_levels= No one,allow_force_push=false | 6 |
| 6 | Process | Release tags are protected | protected_tags | 6 |
| 7 | Process | Threads must be resolved before merging | only_allow_merge_if_all_discussions_are_resolved | 4 |
| 8 | Process | Merge method and squash policy are defined | merge_method,squash_option | 4 |
| 9 | Process | CODEOWNERS exists (enable Code Owner approval on Premium) | repository/files/.gitlab%2FCODEOWNERS | 6 |
| 10 | Knowledge | A default MR template exists | .gitlab/merge_request_templates/Default.md | 7 |
| 11 | Knowledge | The Wiki has a Runbook | projects/:id/wikis | 7 |
| 12 | Planning | A label system and active milestones exist | labels,milestones?state=active | 3 |
How: five-layer troubleshooting model
| Layer | Typical symptoms | Preferred diagnostics |
|---|---|---|
| ① Authentication | 401,Authentication failed,Permission denied (publickey) | glab auth status,ssh -T git@gitlab.com, token expiration date |
| ② Authorization (roles / scopes) | 403,insufficient_scope, private resources 404 | members/all/:user_id,personal_access_tokens/self |
| ③ Protection rules | not allowed to push code to protected branches, push rule rejections | protected_branches,push_rule,GIT_TRACE=1 |
| ④ Tier / deployment model | Setting does not exist, quick action has no effect, API 404 | Tier / Offering at the top of the docs,namespaces of the plan |
| ⑤ Object state | MR cannot be merged, Issue not closed, auto-merge canceled | detailed_merge_status, system notes, project settings |
When: when to re-run the review
- After a new project is created (most configuration can be preset in a project template);
- when team membership changes, and for quarterly access reviews;
- after upgrading the subscription tier (to enable required approvals, push rules, Code Owner approval);
- when an incident review finds that a process was bypassed.
Comparison with similar platforms
| GitLab | GitHub | Azure DevOps | |
|---|---|---|---|
| Built-in compliance view | Compliance center (Ultimate) | Rulesets insights, security overview | Branch policy report |
| Free alternative | This module’s API script | gh api Script | az repos policy list |
remote: GitLab: server message at the start of the output first; it usually states the cause directly.Decision chart: five-layer localization of GitLab collaboration errors
Readiness radar: four dimensions
Readiness scorecard: simulate one automated review
Check the items that your myapp currently satisfies (results are saved in this browser), then click “Run review”. The simulator “calls the API” item by item (the log shows the API paths the lab script actually uses), gives fix commands for items that fail, and calculates the score for each of the four dimensions.
Quick reference for diagnostic commands
| Command | Purpose | What to look for |
|---|---|---|
GIT_TRACE=1 GIT_SSH_COMMAND="ssh -v" git push | Push fails | the key used,remote: GitLab: message |
GIT_CURL_VERBOSE=1 GIT_TRACE=1 git fetch | HTTPS authentication issue | 401 / 403, credential helper |
glab auth status | CLI sign-in status | host, protocol, whether the token is valid |
glab api -i … | API error | status code,RateLimit-*, error JSON |
GLAB_DEBUG_HTTP=1 glab mr list | glab behaves unexpectedly | the requests actually sent |
glab api personal_access_tokens/self | Token information | scopes,expires_at,active |
glab api projects/:id/members/all/:uid | a person’s effective role | access_level |
glab api projects/:id/merge_requests/:iid | Why an MR cannot be merged | detailed_merge_status |
GIT_TRACE=1 GIT_SSH_COMMAND="ssh -v" git push origin main 2>&1 | grep -E 'Offering public key|Authenticated|remote: GitLab|rejected'
debug1: Offering public key: /home/alice/.ssh/id_ed25519_gitlab ED25519 SHA256:… explicit debug1: Authenticated to gitlab.com ([172.65.251.78]:22) using "publickey". remote: GitLab: You are not allowed to push code to protected branches on this project. ! [remote rejected] main -> main (pre-receive hook declined)
Interpretation: Authentication (layer ①) has passed (Authenticated); the problem is at layer ③, protection rules. Common errors: With multiple keys, ssh offers another account’s key first, so you are rejected as “another person” — in ~/.ssh/config the SSH config, use IdentitiesOnly yes.
# A user’s effective role in the project
UID_BOB=$(glab api "users?username=bob" | python3 -c 'import sys,json;print(json.load(sys.stdin)[0]["id"])')
glab api "projects/:id/members/all/$UID_BOB" | python3 -c 'import sys,json;m=json.load(sys.stdin);print(m["username"], m["access_level"], m.get("expires_at"))'
Lab 8: Run the collaboration readiness review automatically (about 6 minutes)
~/gitlablab/gitlab_ready.py:
#!/usr/bin/env python3
"""Collaboration readiness review: python3 gitlab_ready.py mygroup-lab/myapp (requires a signed-in glab)"""
import json
import subprocess
import sys
import urllib.parse
proj = sys.argv[1]
P = urllib.parse.quote(proj, safe="")
G = urllib.parse.quote(proj.rsplit("/", 1)[0], safe="")
def api(path):
r = subprocess.run(["glab", "api", path], capture_output=True, text=True)
return json.loads(r.stdout) if r.returncode == 0 and r.stdout.strip() else None
p = api(f"projects/{P}") or {}
g = api(f"groups/{G}") or {}
pb = api(f"projects/{P}/protected_branches/main") or {}
members = api(f"projects/{P}/members/all?per_page=100") or []
wikis = api(f"projects/{P}/wikis") or []
checks = [
("People", "Top-level group enforces 2FA", bool(g.get("require_two_factor_authentication"))),
("People", "Maintainer or higher ≤ 3", sum(m["access_level"] >= 40 for m in members) <= 3),
("People", "Project visibility is private", p.get("visibility") == "private"),
("Process", "Default branch main is protected", p.get("default_branch") == "main" and bool(pb)),
("Process", "main forbids direct pushes and force pushes",
any(a["access_level"] == 0 for a in pb.get("push_access_levels", [])) and pb.get("allow_force_push") is False),
("Process", "Tags are protected", bool(api(f"projects/{P}/protected_tags"))),
("Process", "Threads must be resolved before merging", p.get("only_allow_merge_if_all_discussions_are_resolved") is True),
("Process", "Merge method and squash policy are defined", p.get("merge_method") in ("merge", "rebase_merge", "ff")
and p.get("squash_option") in ("default_on", "always")),
("Process", "CODEOWNERS exists", api(f"projects/{P}/repository/files/.gitlab%2FCODEOWNERS?ref=main") is not None),
("Knowledge", "Default MR template exists",
api(f"projects/{P}/repository/files/.gitlab%2Fmerge_request_templates%2FDefault.md?ref=main") is not None),
("Knowledge", "Wiki has a Runbook", any(w.get("slug", "").lower() == "runbook" for w in wikis)),
("Planning", "Label system and active milestones exist",
len(api(f"projects/{P}/labels") or []) >= 5 and bool(api(f"projects/{P}/milestones?state=active"))),
]
ok = 0
for cat, name, passed in checks:
ok += passed
print(f"[{'PASS' if passed else 'FAIL'}] {cat:<2} {name}")
print(f"\nScore {ok}/{len(checks)} = {round(ok * 100 / len(checks))}%")
sys.exit(0 if ok == len(checks) else 1)cd ~/gitlablab && python3 gitlab_ready.py "$GL_PROJECT"; echo "exit=$?"
[PASS] People Top-level group enforces 2FA [PASS] People Maintainer or higher ≤ 3 [PASS] People Project visibility is private [PASS] Process Default branch main is protected [PASS] Process main forbids direct pushes and force pushes [PASS] Process Tags are protected [PASS] Process Threads must be resolved before merging [PASS] Process Merge method and squash policy are defined [PASS] Process CODEOWNERS exists [PASS] Knowledge Default MR template exists [PASS] Knowledge Wiki has a Runbook [PASS] Planning Label system and active milestones exist Score 12/12 = 100% exit=0
cd ~/gitlablab/myapp glab api projects/:id -X PUT -F only_allow_merge_if_all_discussions_are_resolved=false >/dev/null python3 ../gitlab_ready.py "$GL_PROJECT" | grep FAIL glab api projects/:id -X PUT -F only_allow_merge_if_all_discussions_are_resolved=true >/dev/null # fix
[FAIL] Process Threads must be resolved before merging
Case 1: “Temporarily loosening protection” became permanent
Problem: During an urgent fix, a Maintainer changed main’s Allowed to push to Developers and forgot to restore it; three months later, 40 commits were found to have bypassed review. Solution: The readiness review script runs daily in a scheduled pipeline (Lesson 2) and notifies on failure; urgent fixes also go through an MR (two Maintainers can approve quickly). Limitation: Premium group-level protected branches can prevent casual loosening at the project level; Ultimate audit events can trace who changed the protection rules.
Case 2: A new hire gets stuck on “Permission denied (publickey)” on day one
Problem: A new hire failed to clone the repository by following the Wiki. Solution: Using the five-layer model: ① Authentication — the SSH key was not added, or ssh offered the wrong key; ② Authorization — not yet added to the group. Add to the onboarding checklist ssh -T git@gitlab.com and glab auth status two self-check commands (Module 0 of this lesson). Limitation: When a group enforces 2FA, members who have not set up 2FA cannot access it after the grace period.
Case 3: MR shows “Ready to merge” but the merge API returns 405
Problem: The release bot’s merge API call failed right after the MR was pushed. Cause: Mergeability is computed asynchronously, so right after a push the status may still be detailed_merge_status or checking / preparing. Solution: The bot polls until mergeable, or uses auto-merge directly (glab mr merge --auto-merge), and include --sha.
Interactive troubleshooting tree
Start from the symptom, make step-by-step choices, and finally get the diagnostic command and fix.
Common errors and fixes
git@gitlab.com: Permission denied (publickey).
Cause: The SSH public key is not added to the account, has expired, or ssh used the wrong private key.
ssh -vT git@gitlab.com 2>&1 | grep -E 'Offering|Authenticated|denied' ssh-add -l
Fix: Add the public key under Edit profile → SSH Keys (check the expiration date); in ~/.ssh/config the SSH config, specify IdentityFile and IdentitiesOnly yes.
remote: HTTP Basic: Access denied. … fatal: Authentication failed for 'https://gitlab.com/mygroup-lab/myapp.git/'
Cause: HTTPS authentication with the account password after 2FA is enabled; or the PAT has expired or lacks read_repository/write_repository (or api) scope.
git config --get-all credential.helper glab auth status
Fix: Switch to SSH, or use the PAT as the password; you can also glab auth login --setup-git-credential-helper have glab provide the credentials. Clear old cached credentials (such as macOS Keychain or Windows Credential Manager).
remote: The project you were looking for could not be found or you don't have permission to view it.
Cause: The path is wrong, or you are not a member of this private project (same reasoning as the API’s 404).
git remote -v glab api "projects/$(git remote get-url origin | sed -E 's#.*gitlab.com[:/]##; s#\.git$##; s#/#%2F#g')" | head -c 150
Fix: Confirm the path and capitalization; ask a group Owner to add you as a member.
MR page: Merge blocked / API detailed_merge_status = not_approved
Cause: The approval rules of a Premium project are not satisfied (for example, 2 approvals or Code Owner approval is required; the author’s own approval does not count by default).
glab api projects/:id/merge_requests/1/approval_state | python3 -m json.tool | head -40
Fix: Request approval from the reviewers named in the matching rule; check whether new commits removed the approvals.
1. Check the scopes and expiration date of the current token.
glab api personal_access_tokens/self | python3 -c 'import sys,json;t=json.load(sys.stdin);print(t["scopes"], t["expires_at"], t["active"])'
2. With one command, determine why MR !5 currently cannot be merged.
glab api projects/:id/merge_requests/5 | python3 -c 'import sys,json;print(json.load(sys.stdin)["detailed_merge_status"])'
A colleague reports: “I can see myapp on the web, but git push origin feat/x the push is rejected with the message “You are not allowed to push code to this project.” Analyze the possible causes and verification commands using the five-layer model.
Being able to see the web page means authentication (①) and read permission are fine. “not allowed to push code to this project” (not protected branches) indicates layer ②: the role is below Developer (for example, Reporter or Planner), or the push is made under the wrong identity (SSH used another account’s key). Verify by: ssh -T git@gitlab.com checking the username in the welcome message; glab api projects/:id/members/all/<uid> checking access_level. Fix: change the role to Developer, or correct the SSH key configuration. If the message mentions protected branches, it is layer ③, but feat/x the branch is usually not protected; check whether a wildcard protection rule applies.
Verified instructional videos
No verified video specifically covering the “collaboration readiness review” was found; a storyboard script is provided.
Official documentation
Video storyboard (about 90 seconds)
This course material cannot generate video or MP3 directly; the storyboard and narration script are provided.
Visual: twelve check cards flip over, with green PASS and red FAIL mixed together; the radar chart gradually fills up.
Narration: The collaboration readiness review turns the first seven modules into twelve automatically executable checks.
Visual: an error falls step by step down a five-step staircase: authentication, authorization, protection rules, tier, state; it is caught at the third step.
Narration: When you hit an error, rule out layers one by one starting from authentication. The server message that begins with “remote: GitLab” often tells you the answer directly.
Visual: a scheduled job runs the review script every day; one day a FAIL appears, which automatically creates an Issue and notifies the Maintainer.
Narration: Configuration drifts, so reviews must run automatically on a schedule. In Lesson 2 we will put it into a pipeline.
Command cheat sheet
Sign-in and environment
brew install glab glab auth login # interactive echo "$T" | glab auth login --hostname gitlab.com --stdin glab auth status ssh -T git@gitlab.com glab api version glab api user
Groups and projects
# Top-level group: can only be created in the UI (GitLab.com) glab api groups -X POST -f name=platform -f path=platform -F parent_id=$GID glab repo create mygroup-lab/myapp --private --defaultBranch main glab repo clone mygroup-lab/myapp glab api "projects/:id/members/all" glab api groups/$GID/members -X POST -F user_id=$U -F access_level=30 -f expires_at=2026-12-31
Issues, labels, milestones
glab issue create -t "Title" -d "Description" -l "type::feature" -m v1.0 -y glab issue list -m v1.0 -l "type::bug" glab issue note 1 -m '/label ~"workflow::doing"' glab issue close 3 glab api projects/:id/labels -X POST -f name=bug -f color='#d9534f' glab api projects/:id/milestones -X POST -f title=v1.0 -f due_date=2026-12-01 glab api projects/:id/issues/1 -X PUT -f add_labels=x -f remove_labels=y
Merge Request
glab mr create -b main -t "Title" -d "Closes #1" --draft -y git push -o merge_request.create -o merge_request.target=main \ -o merge_request.auto_merge -o merge_request.remove_source_branch origin HEAD glab mr list --reviewer=@me glab mr checkout 1 glab mr approve 1 glab mr rebase 1 glab mr merge 1 --squash --remove-source-branch --sha <SHA> -y glab api projects/:id/merge_requests/1 # detailed_merge_status
API tips
glab api projects/:id/merge_requests --paginate --output ndjson
glab api -i user # response headers / rate limits
GLAB_DEBUG_HTTP=1 glab mr list # view actual requests
glab api graphql -f query='query { currentUser { username } }'
curl -H "PRIVATE-TOKEN: $T" https://gitlab.com/api/v4/projects/mygroup-lab%2Fmyapp
glab api personal_access_tokens/self # scopes and expiration dateProtection and rules
glab api projects/:id/protected_branches glab api projects/:id/protected_branches/main -X DELETE glab api projects/:id/protected_branches -X POST -f name=main \ -F push_access_level=0 -F merge_access_level=40 -F allow_force_push=false glab api projects/:id/protected_tags -X POST -f name='*' -F create_access_level=40 glab api projects/:id/push_rule -X POST -f commit_message_regex='^(feat|fix): ' # Premium glab api projects/:id -X PUT -f merge_method=ff -f squash_option=always
Wiki, notifications, search
glab api projects/:id/wikis -X POST -f title=Runbook -F content=@runbook.md glab api projects/:id/notification_settings -X PUT -f level=participating glab api "projects/:id/search?scope=blobs&search=healthz" glab api todos
Troubleshooting
GIT_TRACE=1 GIT_SSH_COMMAND="ssh -v" git push GIT_CURL_VERBOSE=1 git fetch glab api projects/:id/members/all/$UID glab api projects/:id/merge_requests/1/approval_state python3 gitlab_ready.py mygroup-lab/myapp
Quick actions and GFM shorthand
| Scenario | Syntax |
|---|---|
| Issue / MR general | /assign me /label ~x /unlabel ~x /milestone %v1.0 /due 2026-12-01 /estimate 2h /spend 30m /close /reopen /confidential |
| MR only | /draft /ready /approve /assign_reviewer @x /rebase /merge |
| Premium | /weight 3 /epic &1 /iteration |
| Reference | @user #1 !1 &1 ~label %v1.0 $1 [[Page]] group/project#1 #1+ |
| Close Issue | Closes #1 / Fixes / Resolves / Implements (merge into default branch) |
Quick troubleshooting table
| Symptom | Most likely cause | First command |
|---|---|---|
Permission denied (publickey) | SSH key not added / wrong key used | ssh -vT git@gitlab.com |
HTTP Basic: Access denied | Password used after 2FA; PAT expired | glab auth status |
not allowed to push code to protected branches | main is protected | glab api projects/:id/protected_branches |
401 Unauthorized | Not authenticated / token invalid | glab api personal_access_tokens/self |
403 insufficient_scope | Insufficient scope | Same as above; check scopes |
404 Project Not Found | No permission or path not encoded | glab api projects/mygroup-lab%2Fmyapp |
| MR cannot be merged | Draft / conflicts / threads / approvals / rebase needed | detailed_merge_status |
| Issue did not close automatically | keyword, target branch, project settings | glab api projects/:id → autoclose_referenced_issues |
| Setting cannot be found | Tier / role / deployment model | Tier / Offering at the top of the docs |
Recommended baseline configuration (myapp)
| Location | Setting |
|---|---|
| Group → Settings → General → Permissions | Enforce 2FA; Roles allowed to create projects = Maintainer |
| Project → Settings → General | Visibility = Private |
| Project → Settings → Merge requests | Merge commit (or FF); Squash = Encourage; delete source branch by default; all threads must be resolved; (Lesson 2) pipeline must succeed |
| Project → Settings → Repository → Branch rules | main: push = No one, merge = Maintainers, force push off; (Premium) Code Owner approval |
| Project → Settings → Repository → Protected tags | *: create = Maintainers |
| Repository | .gitlab/CODEOWNERS,.gitlab/merge_request_templates/Default.md |
| Wiki | Runbook page |
Integrated lab + final quiz
mygroup-lab/myapp-final from scratch (delete it when finished, and keep myapp for Lesson 2).glab auth status && ssh -T git@gitlab.com
echo "$GL_GROUP $GL_PROJECT"
glab api "groups/$GL_GROUP" | python3 -c 'import sys,json;g=json.load(sys.stdin);print(g["full_path"], g["visibility"], g.get("require_two_factor_authentication"))'export FP="$GL_GROUP/myapp-final"
cd ~/gitlablab && glab repo create "$FP" --private --defaultBranch main
cd myapp-final 2>/dev/null || { git clone "git@gitlab.com:$FP.git" && cd myapp-final; }
cp ../myapp/{app.py,requirements.txt,requirements-dev.txt,Dockerfile,.gitignore,README.md} . && cp -r ../myapp/tests .
git switch -c main 2>/dev/null || true
git add . && git commit -qm "feat: import myapp" && git push -u origin mainv1.0, and create the Issue “Add version endpoint”.
for L in "type::feature:#1d63ed" "type::bug:#d9534f" "type::docs:#6c757d" "workflow::doing:#f0ad4e" "workflow::review:#5cb85c" "priority::high:#b42318"; do
glab api projects/:id/labels -X POST -f name="${L%:*}" -f color="${L##*:}" >/dev/null; done
glab api projects/:id/milestones -X POST -f title=v1.0 -f due_date=$(date -d '+14 days' +%F) >/dev/null
glab issue create -t "Add /version endpoint" -d "Returns APP_VERSION" -l "type::feature" -m v1.0 -yglab api projects/:id -X PUT -f merge_method=merge -f squash_option=default_on \ -F remove_source_branch_after_merge=true -F only_allow_merge_if_all_discussions_are_resolved=true >/dev/null glab api projects/:id/protected_branches/main -X DELETE glab api projects/:id/protected_branches -X POST -f name=main -F push_access_level=0 -F merge_access_level=40 -F allow_force_push=false >/dev/null glab api projects/:id/protected_tags -X POST -f name='*' -F create_access_level=40 >/dev/null
git switch -c feat/version
cat >> app.py <<'EOF'
@app.get("/version")
def version():
return jsonify(version=os.getenv("APP_VERSION", "dev"))
EOF
cat >> tests/test_app.py <<'EOF'
def test_version(monkeypatch):
monkeypatch.setenv("APP_VERSION", "1.0")
assert app.test_client().get("/version").get_json() == {"version": "1.0"}
EOF
mkdir -p .gitlab/merge_request_templates
printf '* @@maintainer\n\n[App]\n/app.py @%s\n' "$GL_USER" > .gitlab/CODEOWNERS
printf '## Changes\n\n## Related\nCloses #\n\n## Verification\n- [ ] pytest\n' > .gitlab/merge_request_templates/Default.md
. ../myapp/.venv/bin/activate && REDIS_HOST=127.0.0.1 pytest -q
git add -A && git commit -qm "feat: add /version endpoint, CODEOWNERS and MR template"
git push -u origin feat/version
glab mr create -b main -t "Add /version endpoint" -d "Closes #1" -l "type::feature" -m v1.0 -y
When working on the original myapp,#1 is already closed, so change Closes #1 and the numbers in the subsequent commands to the number of the Issue created in Step 3 (glab issue list view it).
detailed_merge_status (should be discussions_not_resolved) → resolve the thread → glab mr approve 1 → glab mr merge 1 --squash -y → glab issue view 1 shows closed.glab api projects/:id/wikis -X POST -f title=Runbook -F content=@/tmp/runbook.md to create the Runbook; set project notifications to Custom and enable failed_pipeline.python3 ~/gitlablab/gitlab_ready.py "${FP:-$GL_PROJECT}"
git switch main && git pull -q && echo test >> README.md && git commit -qam "docs: test" && git push origin main; git reset -q --hard origin/main
The review script should score 12/12; a direct push to main should be rejected. Cleanup (only when redoing): glab api "projects/$(printf %s "$FP" | sed 's#/#%2F#g')" -X DELETE (GitLab.com may have delayed deletion enabled, so the project first enters a pending-deletion state). Keep mygroup-lab and mygroup-lab/myapp, as Lesson 2 will add on top of them .gitlab-ci.yml, a Runner and “the pipeline must succeed”.
Open-ended self-test (answer first, then expand the reference answer)
1. Why is it said that “the tier is determined by the top-level group”? What does this mean for project structure design?
The subscription (Free / Premium / Ultimate), user limit, compute minutes and storage quota are all attached to the top-level namespace, and subgroups and projects inherit them. So projects that need Premium features must be placed under a top-level group that has purchased Premium; putting team projects in a personal namespace means they cannot benefit from group subscriptions.
2. A git push push to a protected branch is rejected: what steps did the server go through?
Shell / Workhorse receives → Gitaly’s receive-pack runs pre-receive → calls the Rails internal API /api/v4/internal/allowed Checks: project access and role, push / force push permission on protected branches, (Premium) push rules and CODEOWNERS → if any fails, the push is rejected, the ref is unchanged, and the client sees remote: GitLab: … and pre-receive hook declined.
3. On the Free tier, how can you get as close as possible to “enforced review”?
Protected branch with push = No one, merge = Maintainers; a non-author Maintainer merges; enable “all threads must be resolved”; after Lesson 2, enable “the pipeline must succeed”; use the readiness script to detect configuration drift. True required approvals need Premium.
4. Board dragging, quick actions /label, REST add_labels What is the relationship among the three?
All of them change the labels field of an Issue. A board column is a label query: dragging = removing the source column label + adding the target column label; quick actions and the API change labels directly, and the board updates accordingly. Scoped label mutual exclusion (Premium) applies in all three ways.
5. When should you use GraphQL and when REST? What should you watch for regarding rate limits?
Use GraphQL when you need to fetch multiple levels of nested data in one go (MR + approvals + pipeline); use REST for simple write operations and scenarios with the most documentation examples. GraphQL has limits such as a complexity of 250, 10,000 characters per query, and a 30-second timeout; REST needs to handle pagination and 429 responses using the Retry-After,glab api does not retry automatically.
6. Which kinds of teams suit each of the three merge methods?
Merge commit: preserves the merge point for each MR; the most flexible and suits most teams. Semi-linear: keeps merge points but requires rebasing first, so the history is tidy. Fast-forward: fully linear; with Squash: Require, each MR becomes one commit; suits teams that value git bisect teams, but with many MRs it requires frequent rebasing (the Premium merge train helps).
Final quiz (12 questions covering all modules)
Sources and version notes
| Topic | Verified finding | Source (accessed 2026-11-16) |
|---|---|---|
| GitLab versions and cadence | A minor version is released on the third Thursday of each month: 18.11.0 (tagged 2026-04-15), 19.0.0 (2026-05-21), 19.5.0 (2026-10-15); patches 19.5.6 / 19.4.8 / 19.3.9 released on 2026-11-16; the latest version is 19.5 (19.5.6), and 19.6 has not yet been released (the release page shows Upcoming) | docs.gitlab.com/releases · gitlab-org/gitlab repository tags (queried via the GitLab API) |
| glab | v1.130.0 (2026-11-10); the official installation methods are Homebrew and release binaries; glab auth login supports --stdin,--web,--device (17.9+),--job-token, and by default stores the token in the system keyring | gitlab-org/cli releases · glab auth login · glab api |
| Deployment models | Dedicated: single-tenant, GitLab-hosted, AWS (Azure/GCP not supported), customer-selected region, customer-owned KMS can be used, Ultimate | GitLab Dedicated |
| Tiers and pricing | Free $0 / Premium $29 per user per month (billed annually) / Ultimate contact sales; compute minutes 400 / 10,000 / 50,000; Free repository 10 GiB; a private top-level group on Free has at most 5 users, beyond which it is read-only | Pricing · GitLab.com settings · Free user limit · Compute minutes |
| Hosted runners (preview of Lesson 2) | Untagged jobs run on saas-linux-small-amd64 (2 vCPU / 8 GB); job timeout 3 hours | Hosted runners on Linux |
| Roles | Minimal Access(5) / Guest(10) / Planner(15, introduced in 17.7) / Reporter(20) / Security Manager(25, 18.11 Beta) / Developer(30) / Maintainer(40) / Owner(50); Planner can pull code since 18.7; custom roles Ultimate; Minimal Access only in Premium/Ultimate top-level groups | Roles and permissions · Members API · Custom roles |
| Groups | Subgroups up to 20 levels (recommended ≤5); a child role cannot be lower than the inherited role; GitLab.com top-level groups can only be created in the UI; GitLab.com does not offer Internal visibility | Subgroups · Groups API · Project and group visibility |
| Planning | Epic: Premium, sub-Epics Ultimate, as work items 17.2 Beta → 18.1 GA; scoped labels Premium; boards Free: multiple project boards / one group board; drag rules | Epics · Labels · Issue boards · Closing issues |
| MR | Three merge methods and four squash options; auto-merge Free (enhanced version GA in 17.7); push option merge_when_pipeline_succeeds deprecated in 17.11 → auto_merge; Free optional approval; required approvals and approval settings Premium (author approval blocked by default, all approvals removed by default on new commits); detailed_merge_status values | Merge methods · Auto-merge · Approval settings · MR API · Push options |
| API and tokens | GraphQL complexity 250/200, 10,000 characters, 30 seconds; current rate limits: authenticated 2,000 requests/minute/user, unauthenticated 500 requests/minute/IP, with the new per-plan limits marked “not yet in effect”; PAT default and maximum 365 days; fine-grained PAT 18.10 Beta → 19.2 GA (Free); project access tokens on GitLab.com require Premium | GraphQL · Rate limits · PAT · Fine-grained PAT · Project access tokens |
| Protection | Protected branch options, wildcards take the most permissive, group-level protected branches Premium; push rules Premium (rule list); CODEOWNERS Premium, location priority, sections / optional sections / number of approvals / @@role | Protected branches · Push rules · Code Owners · CODEOWNERS syntax |
| Productivity | Wiki is an independent Git repository, format and _sidebar; notification levels and inheritance,X-GitLab-NotificationReason; exact code search Premium, GA in 19.5; GFM reference syntax; shortcuts; description template paths and Default.md | Wiki · Notifications · Exact code search · GFM · Shortcuts · Templates |
Video verification notes
The following videos were verified via the YouTube oEmbed interface (https://www.youtube.com/oembed?url=…&format=json, 2026-11-16) verified the titles and channels: GitLab “What is GitLab Dedicated? Secure DevSecOps for Enterprise” (Bi6t_T8Ktso), “Plan and Track Work - Setting up your Organization with GitLab (v2) (HD)” (7ICcIaDsVc8), “GitLab issue boards demo” (CiolDtBIOA0), “GitLab Epics - Setting up your Organization with GitLab (v2) (HD)” (c0EwYYUZppw), “Issues, Merge Requests and Integrations in GitLab” (raXvuwet78M), “Code Owners - The basics (HD)” (P5dR5Z9vVeM); GitLab Unfiltered “GitLab 201: How to Create an Epic” (hxUmalpYHF4), “GitLab 101: Creating a Merge Request” (etgjyJ0SSUM), “Remote Development - Workspaces CLI Support” (0lH4qiusjwo); CloudThat “GitLab Explained: What's GitLab? Its Benefits & Usage” (gSkhXIaSC44); AL HUGHES “Managing Projects with GitLab | ISSUES, EPICS & MILESTONES” (TWME_7KNrKA); Dan Gitschooldude “038 Gitlab Merge Request Merge Methods” (x6vD9RHEB1M); Blujay Technologies “GitLab Merge Request | How to Create, Review & Approve Merge Requests in GitLab” (d0HpoFvUJh8); Latio - Learn Security Together “How to Setup GitLab Protected Branches, as fast as possible” (AB-8q0fMiKk); ReleaseTEAM “GitLab Approval Rules on Merge Requests” (FpRCO_qfbWE); The Debug Zone “remote: GitLab: You are not allowed to push code to protected branches on this project” (8is_5fACwBY); TechWorld with Nana “GitLab CI CD Tutorial for Beginners [Crash Course]” (qP8kir2GUgo). oEmbed does not return duration or publication date, so durations are not shown on the cards. Most videos were recorded before GitLab 19; the interface and tiers follow this lesson and the official docs. No verified videos specifically on group inheritance and roles, glab introduction / GraphQL, Wiki / notifications / search, or the collaboration readiness review were found; storyboard scripts are provided instead.
Narration audio notes
The “Audio” page reads the script aloud in real time using the browser’s Web Speech API (speechSynthesis, en-US), and pronounces English terms with en-US. Results depend on the voices installed in the operating system (for example Windows “Microsoft Xiaoxiao/Yunxi” or macOS “Tingting”). This course material cannot call a TTS service, so no MP3 is embedded; for offline audio, pass the script to a TTS service.
Known limitations
- All commands in this lesson have not been run on a real GitLab.com account; the “expected output” sections are examples compiled from the official docs examples, where IDs, SHAs, times, numbers, usernames (alice, bob) and version strings (such as
19.5.6-ee) are illustrative values, and glab’s output format also varies between versions. - Error messages follow the official docs and common actual output; messages marked “wording may differ slightly” (such as the Free-tier read-only notice, protected tags, CODEOWNERS push rejections and inherited-role validation) have not been verified word for word against the original text.
- The official docs do not currently state clearly the identity verification requirements (credit card / phone number, etc.) for free accounts using GitLab.com hosted runners. This lesson only says “verification may be required; follow the prompts on the sign-up page”, and Lesson 2 will verify this.
- Prices, compute minutes and rate limits may change; the Rate limits page lists both “currently in effect” and “not yet in effect” values, and this lesson uses the values currently in effect.
- This lesson’s baseline is GitLab 19.5 (latest patch 19.5.6, 2026-11-16); 19.6 has not yet been released (the release page shows Upcoming, and the repository had no 19.6.0 tag at verification time). The content was verified against the 19.x docs on 2026-11-16.
- The animations and simulators are simplified versions of the real mechanisms: the permission evaluator covers only a few actions; the push check simulator’s order follows GitLab’s access check logic but does not cover every push rule; the readiness scorecard and GFM parser use simplified rules.
- myapp’s dependencies list only minimum versions (
flask>=3.1etc.), and the base image ispython:3.13-slim; Lesson 2 will pin the versions in CI.