GitLab Hour 1: Core Fundamentals

From “using Git” to “collaborating in GitLab”: platform editions, groups and permissions, planning tools, Merge Requests, glab and the API, branch protection, and collaboration readiness review
GitLab.com (19.x)Self-Managed 19.5.6glab v1.130.0All labs can be completed on the Free tierVerified against docs.gitlab.com · 2026-11-16
Prerequisite course This lesson assumes you have completed the same-repository Git 8-hour course(commits, branches, rebase, SSH keys), especiallyLesson 4on the GitLab repository side (protected branches, approvals, push rules, mirroring). This lesson does not repeat those Git-side operations; instead, it takes a platform perspective, explaining how GitLab organizes people, planning, code review and automation, laying the groundwork for CI/CD from Lesson 2 onward.
Overall learning objectives
  • 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 main configure 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

#TimeModuleCore contentAnimation / interactionLab (GitLab.com Free)
0Before classEnvironment setupGitLab.com account, 2FA, SSH key, PAT, glab installation and sign-inEnvironment self-check checklistglab auth status Pass
100–06Platform overviewThree deployment models, three tiers, release cadence, component architecture, GitLab.com limitsRequest path simulator: which components Web / API / git over SSH / git over HTTPS pass throughCheck version, tier and usage
206–13Groups, subgroups, projects and rolesNamespace hierarchy, member inheritance, visibility, default roles and custom rolesPermission evaluator: inheritance chain + action → allow/denyCreate mygroup-lab, subgroups and mygroup-lab/myapp
313–21Issues, Epics, Boards and milestonesWork items, labels (including scoped labels), milestones, boards, Epics, quick actionsBoard simulator: the label changes and API calls that actually happen when you drag a cardCreate labels, milestone v1.0 and 3 Issues for myapp
421–28Merge Request end to endReview threads, suggestions, approvals, merge checks, auto-merge, merge methods and squash, closing IssuesCore animation: the platform event flow of one MR from push to mergeUse an MR to deliver myapp’s /healthz
528–35glab and the REST / GraphQL APIcommon glab commands,glab api, REST pagination, GraphQL, tokens and rate limitsREST vs GraphQL call counts and rate-limit countersUse the API to generate an “open MR report”
635–42Protected branches, push rules and CODEOWNERSBranch rules, protected tags, push rules (Premium), CODEOWNERS syntax and approvalsServer-side push check simulator: pre-receive → access check → push rulesProtect main, add CODEOWNERS and verify a rejected push
742–50Wiki, notifications, search and productivityWiki repository, notification levels, to-dos, three search types, GFM references, keyboard shortcuts, description templatesGFM reference parser: recognizes #, !, ~, %, @, & as you typeWrite a runbook wiki, MR template, adjust notifications
850–60Collaboration readiness review and troubleshooting basics12 readiness checks, common errors (rejected push, 401/403/404, MR cannot be merged)Readiness scorecard + interactive troubleshooting treeAutomatically review myapp with a glab api script
—After classCheat sheet · Integrated labBuild a “collaboration-ready” myapp project from scratch, preparing for Lesson 2’s CI/CDFinal quiz (12 questions)Integrated lab

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commands / locationsLab
Determine the required tier and deployment model for a feature✓✓✓✓·✓✓✓Tier/Offering label at the top of the docs pageM1 usage page
Design group hierarchy and member permissions·✓··✓✓·✓glab api groups, members pagemygroup-lab
Plan work with Issues / labels / milestones / boards··✓✓✓·✓·glab issue,glab label, quick actionsMilestone 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, GraphQLMR report / readiness script
Protect the default branch, configure code owners·✓·✓·✓·✓Branch rules, CODEOWNERSRejected push
Knowledge capture and information retrieval··✓···✓·Wiki, search, GFMRunbook
Diagnose common GitLab collaboration errors✓✓·✓✓✓·✓GIT_TRACE,glab api -iTroubleshooting tree

Topics not covered in this lesson (and where to learn them)

TopicWhy not in this lessonWhere to learn
Git internals, branching strategy, SSH/HTTPS authentication details, GitLab mirroringCovered in the Git courseGit 8-hour course, GitLab part in Lesson 4
.gitlab-ci.yml, Runner, caching and artifacts, componentsBelongs to the CI/CD topicLesson 2
Container registry, OIDC deployment to Azure / AWSRequires the pipeline basics from Lesson 2Lesson 3(Azure),Lesson 4(AWS)
Security scanning, compliance frameworks, audit events, GitLab DuoMost require Ultimate; advanced topicsLessons 5–7 (published later)
Self-Managed installation, backup, upgrade and high availabilityThis lesson focuses mainly on GitLab.comOfficial installation docs, operations perspective in Lessons 6–7
Comparison with GitHub Actions, Azure Pipelines, JenkinsThis lesson only does a conceptual comparisonGitHub · Azure DevOps · Jenkins

How to use this course material

10 pages per module
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.
Learning progress
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).
Audio narration
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)

ItemConvention
PlatformMainly 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
NamingTop-level group <your-username>-lab (written in the text as mygroup-lab); project mygroup-lab/myapp; default branch main; glab Signed in
Sample application myappPython 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 lessonsLesson 2 Runner: local containers gitlab-runner, tag lab-docker; Lesson 3 Azure: rg-gitlab-lab / canadacentral; Lesson 4 AWS: ca-central-1 / ECR myapp
Version notes GitLab releases a minor version on the third Thursday of each month: 19.5.0 released on 2026-10-15, with patches 19.5.6 / 19.4.8 / 19.3.9 released on 2026-11-16; 19.6 is not yet released. This lesson’s baseline is GitLab 19.5 (latest patch 19.5.6), all features verified against the 19.x docs (for example, the Planner role was introduced in 17.7, Epics became work items with GA in 18.1, fine-grained personal access tokens reached GA in 19.2, and exact code search reached GA in 19.5). GitLab.com deploys continuously, so new features may appear there slightly earlier than on Self-Managed. The current glab version is v1.130.0 (2026-11-10). The tier of each feature is determined by the Tier / Offering label at the top of its docs page.

Module 0 · Environment setup (complete before class)

GitLab.com account + two-step verification + SSH key + personal access token + glab, about 10 minutes
Before class ≈ 10 minutesGitLab.com Freeglab v1.130.0
Prerequisites
  • 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

  1. 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.
  2. 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.
  3. This lesson’s top-level group will be named <your-username>-lab. Top-level group paths are globally unique on GitLab.com, so the mygroup-lab in the text is only an example; replace it with your own.
Why enable 2FA first Group Owners can require all members to enable 2FA (used in Modules 2 and 8). Also, once 2FA is enabled, HTTPS pushes can no longer use your account password; you must use a personal access token or SSH.

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.

Token facts (verified) If no expiration date is set, it expires after 365 days by default, and 365 days is also the default maximum (Self-Managed administrators can change the limit in 17.6+). Fine-grained personal access token was introduced as a Beta in 18.10,19.2 GA, is available on the Free tier, and can limit permissions to specific resources. For simplicity, this lesson uses the 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.

Environment self-check checklist

Module 1 · GitLab platform overview: deployment models, tiers and architecture

00:00 – 06:00 · One application covers “plan → code → build → secure → deploy → operate”, but which features you can use depends on “where you deploy” and “which tier you buy”
6 minGitLab 19.5 · released monthlyFree / Premium / Ultimate★★★★☆
Learning objectives
  • 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 push and a git request each pass through components among Workhorse, Puma (Rails), Gitaly and Sidekiq.
Prerequisites: Git basics, HTTP/SSH. Importance:★★★★☆ (for tool selection and for understanding why “I can’t see this button”)

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.comGitLab Self-ManagedGitLab Dedicated
ModelMulti-tenant SaaS operated by GitLabYou install and operate it on your own servers / cloud / KubernetesOperated by GitLab as a single-tenant SaaS with fully isolated instances
TiersFree / Premium / UltimateFree (CE or unlicensed EE) / Premium / UltimateUltimate
UpgradesContinuously deployed, always up to dateYou upgrade yourself (one minor version per month, following the upgrade path)Maintained by GitLab on a schedule
Hosting locationGitLab’s cloudAnywhere (Linux packages, Helm Chart, Operator, Docker)AWS, customer chooses the region; customer-owned AWS KMS keys can be used; Azure / GCP not supported
Admin rightsNone (you can only manage your own groups)Full instance administrator (Admin area)Limited instance configuration (through Switchboard, etc.)
Typical reasons to chooseFastest to start, zero operationsData must stay on the internal network; server-side hooks / customization neededNeeds data residency and isolation, but does not want to operate it

How: key boundaries of the three tiers (GitLab.com, verified 2026-11)

FreePremiumUltimate
Price$0$29 / user / month (billed annually)Contact sales (custom pricing)
Compute minutes (hosted runners, per month / per top-level namespace)40010,00050,000
StorageRepository (including LFS) limit 10 GiB500 GiB per project500 GiB per project
UsersPrivate Top-level group has up to 5 users; beyond that it becomes read-only (public groups are not limited)Per seatPer seat
Code review and protectionOptional approvals, protected branches, auto-merge, three merge methodsRequired approvals / approval rules, CODEOWNERS approvals, push rules, merge trains, group-level protected branches+ security approval policies, compliance frameworks
PlanningIssues, labels, milestones, multiple project boardsEpics, scoped labels, iterations, weights, configurable boards+ sub-Epics, health status, OKRs, etc.
SecuritySome scanners (limited result display)Same as FreeFull 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)

ComponentResponsibility
NGINX / load balancerTLS 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
SidekiqBackground 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-sshdHandles git@gitlab.com:… SSH connections, asking the Rails internal API “can this key access this project”
PostgreSQL / RedisPrimary data / cache, sessions, Sidekiq queues
Object storageArtifacts, LFS, uploaded files, packages, image layers
OthersContainer 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

GitLabGitHubAzure DevOps
Organization structureGroups can nest up to 20 levels of subgroupsEnterprise → Organization → Repo (no nesting)Organization → Project → multiple Repos
Code review unitMerge Request (!1)Pull Request (#1)Pull Request
CI/CDBuilt-in .gitlab-ci.yml + RunnerGitHub ActionsAzure Pipelines
Self-hostedSelf-Managed (CE free)GitHub Enterprise Server (paid)Azure DevOps Server

For comparison:GitHub 8-hour course · Azure DevOps 8-hour course.

Common misconceptions① “CE and EE are two different products”: EE includes all of CE’s code; without a license it is Free. Upgrading from CE to EE does not require migrating data. ② “GitLab.com and Self-Managed have exactly the same features”: not quite. GitLab.com has no Admin area, no Internal visibility, and cannot use server-side hooks, while some SaaS-only features (such as hosted runners) must be deployed yourself on Self-Managed. ③ “The Free 5-user limit restricts public open-source projects”: no, it only applies to private top-level groups.

Architecture diagram: GitLab’s main components

Browser / glabHTTPS :443 git clientSSH :22 / HTTPS NGINX → WorkhorseReverse proxy · Git HTTP · uploads GitLab Shellgitlab-sshd Puma (Rails)Web UI · REST v4 · GraphQLPermission checks · /api/v4/internal SidekiqBackground jobs · notifications · pipelines Gitaly (gRPC)All Git reads/writes · Praefect replication PostgreSQL Redis Object storageArtifacts · LFS · packages · uploads Container Registry · Pages · KAS (agent for Kubernetes) · Runner (deployed separately, polls /api/v4/jobs/request)Expanded in Lessons 2–6 allowed? git data flow (Workhorse ↔ Gitaly)
Figure 1-1: Rails decides “whether it is allowed”, Gitaly handles “how Git data is read and written”, Sidekiq handles “the follow-up work after the fact”

Decision chart: can I use this feature?

Want to use a featuree.g., push rules ① Does the offering match?.com / Self-Managed / Dedicated ② Is the tier sufficient?Check top-level group subscription ③ Is the role sufficient?Most settings require Maintainer or higher ④ Feature flag / Beta?flag in the docs History ✓ Can use it
Figure 1-2: the tier is determined by the top-level group (or personal namespace) subscription; subgroups and projects inherit it automatically

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).

Client Workhorse(after NGINX) GitLab Shell Puma / RailsAuthentication · authorization PostgreSQL Redis Gitaly Sidekiq Notifications /Pipelines
Choose an operation above, then click “Play”.
$ # Waiting for operation

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 / locationPurposeNotes
glab api versionView instance version (requires authentication)Returns version,revision,enterprise
glab api metadataMore detailed metadata (including KAS information)Requires authentication; also applies to Self-Managed
glab api namespacesView your namespaces and their planOn GitLab.com, returns plan field (free / premium / ultimate, etc.)
Group → Settings → Usage quotasCompute minutes, storage and seat usageVisible to Owner
https://gitlab.com/helpView version on the webVisible after signing in
sudo gitlab-rake gitlab:env:infoSelf-Managed: environment and version informationLinux 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)

Confirm version and identity:
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.

Check tier: 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.
Find the usage page on the web: Avatar → Edit profile → Usage quotas, and note the current values for “Compute minutes” and “Storage” (Lesson 2 will consume compute minutes).
Read the tier label on a docs page: Open Push rules, and confirm the top says Tier: Premium, Ultimate; then open Auto-merge, and confirm it is Free, Premium, Ultimate. Make a habit of checking these two lines first.
Cleanup: This lab is read-only; no cleanup needed.
Cost / permissions / risks Cost: 0; requires a signed-in PAT (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.

Command-line questions
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"])'
Scenario analysis
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

▶
What is GitLab Dedicated? Secure DevSecOps for Enterprise — GitLab
Official channel · English · introduces Dedicated’s single-tenant isolation and data residency
▶
GitLab Explained: What's GitLab? Its Benefits & Usage — CloudThat
English · introduction to platform concepts (third-party; the interface may be dated)

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.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–75s
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.
Shot 4 · 75–90s
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.
or score ≥ 70% on the quiz

Module 2 · Groups, subgroups, projects and role permissions

06:00 – 13:00 · Structure determines permissions: members inherit from the top down, and lower levels can only “add” permissions, never “remove” them
7 minPlanner role since 17.7Custom roles: Ultimate★★★★★
Learning objectives
  • Design an organizational structure with top-level group → subgroup → project, and explain mygroup-lab/myapp the 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.
Prerequisites: Module 1’s “tier is determined by the top-level group”. Importance:★★★★★ (variables, runners and deployment permissions in all later lessons are attached to this structure)

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)

RoleTypical usersKey capabilities (project level)
Minimal AccessPeople 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
GuestExternal stakeholdersCreate Issues and comment; in private projects,cannot see code by default
Planner (introduced in 17.7)Product managers, project managersCreate / edit Issues, Epics, milestones and Wiki pages, view confidential Issues; since 18.7 can pull code; cannot push
ReporterQA, read-only developers, operationsPull code, manage labels and milestones, view pipelines; cannot push
Security Manager (18.11 Beta)Security teamSecurity-related capabilities; sits between Reporter and Developer but is not a strict superior/subordinate level
DeveloperDevelopersPush to non-protected branches, create MRs, approve MRs, run pipelines; by default cannot push to or merge into protected branches
MaintainerTech leadsPush to / merge into protected branches, change project settings and branch rules, add project members
OwnerGroup administratorsDelete / 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

  1. Group members enter all subgroups and projects with the same role (shown on the members page as Inherited).
  2. 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.
  3. 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”.
  4. 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

GitLabGitHubAzure DevOps
HierarchyGroups can nestOrganization + Teams (teams can nest; repositories do not)Organization → Project
RolesGuest/Planner/Reporter/Developer/Maintainer/OwnerRead/Triage/Write/Maintain/AdminReaders/Contributors/Project Administrators (security groups)
Fine-grainedCustom roles (Ultimate)Custom repository roles (Enterprise)Per-object ACLs
Common misconceptions① “Changing an inherited Maintainer to Developer within a project”: not possible; it can only be changed at the upper level. ② “Developers can merge into main”: not by default, since 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

mygroup-lab (top-level group)alice Owner · bob Developer · pm PlannerSubscription / user limit / 2FA enforcement myapp (project)alice Owner · bob Developer · pm PlannerAll Inherited platform (subgroup)bob → Maintainer(direct member, upgraded)carol Reporter (only here) platform/infrabob Maintainer · carol Reporter ✗ Cannot demote bob to Reporter in myappA child role cannot be lower than the inherited role
Figure 2-1: Members inherit downward; lower levels can only “upgrade”. carol is visible only in the platform subtree

Permission ladder: which actions require which role

Guest PlannerEpic · milestone · Wiki ReporterPull code · labels DeveloperPush to non-protected branchesCreate / approve MR MaintainerMerge into mainProject settings · members OwnerDelete / archive projectGroup settings · billing Create Issue
Figure 2-2: The dividing line between Developer and Maintainer is “protected branches”, which sets up Modules 4 and 6

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.

mygroup-lab (inheritance source)
platform subgroup (direct member)
project platform/infra (direct member)
Action:
Select a role and action, then click “Evaluate”.
$ glab api projects/mygroup-lab%2Fplatform%2Finfra/members/all/BOB_ID

Core commands

CommandPurposeKey parameters / notes
Web: New groupCreate top-level groupOn GitLab.com, top-level groups can only be created in the UI (the API does not allow it)
glab api groups -X POSTCreate subgroup-f name= -f path= -F parent_id=
glab repo create GROUP/NAMECreate project--private,--defaultBranch main,--readme,-d description
glab api groups/:id/members -X POSTAdd members-F user_id= -F access_level=30 -f expires_at=YYYY-MM-DD
glab api projects/:id/members/allList all members, including inherited ones/members Returns direct members only
glab api projects/:id/share -X POSTShare 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)

Create the top-level group in the UI: In the upper-left corner + → New group → Create group. Enter the Group name and URL as <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
Group-level security settings: Group → Settings → General → Permissions and group features: select Require all users in this group to set up two-factor authentication(grace period can be set to 48 hours); set Roles allowed to create projects to Maintainer. Save.
Create the subgroup (see the “Commands” page):
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
Create the myapp project and write the initial code (Flask + gunicorn + Redis counter, port 5000; /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.md
Run tests locally, then push:
python3 -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.

(Optional) Invite a colleague: If you have a second GitLab account, invite it with the Developer role and a 30-day expiration to 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.

Verify and keep: 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).
Cost / permissions / risks Cost: 0; requires an account that can create groups; risk: setting a project to Public by mistake would expose the code. Under a private group the system blocks creating public projects, which is exactly the value of the visibility constraint.

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.

Command-line questions
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]'
Scenario analysis
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

▶
Plan and Track Work - Setting up your Organization with GitLab (v2) (HD) — GitLab
Official channel · English · “Setting up your Organization” series, covering how to organize groups and projects (recorded earlier; for newer roles such as Planner, follow this lesson)

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.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–65s
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.
Shot 4 · 65–80s
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.
or score ≥ 70% on the quiz

Module 3 · Issues, Epics, Boards and milestones

13:00 – 21:00 · A board is just “a list of Issues grouped by label”; dragging a card is essentially changing a label; milestones manage time, Epics manage themes
8 minIssue · milestone · board: FreeEpic · scoped labels · iterations: Premium★★★★☆
Learning objectives
  • Set up a label system for myapp (type / workflow / priority), understand the difference between group labels and project labels, and scoped labels’ key::value mutually exclusive behavior (Premium).
  • Use milestones to v1.0 plan 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.
Prerequisites: Module 2 roles (Guests can create Issues; Planners and Reporters can manage labels and milestones). Importance:★★★★☆

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.

ObjectScopeLevelTypical use
IssueProjectFreeA deliverable requirement / defect that can be closed by an MR
TaskProject (child of an Issue)FreeSplits an Issue into checkable small items; each Task can also have an assignee
IncidentProjectFree (some features paid)Production incidents (Lessons 5–7)
EpicGroupPremium; sub-Epics UltimateCross-project themes / features, summarizing progress across multiple Issues
MilestoneProject or groupFreeTimebox: a release or sprint, with start / due dates and burndown data
IterationGroup (iteration cadence)PremiumFixed-cycle sprints that roll over automatically
LabelProject or groupFree; scoped labels PremiumCategories, 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

  1. 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.
  2. Scoped labels (Premium): the title contains ::, and only one label from the same scope (workflow::) can be on an object at a time; adding workflow::review automatically removes workflow::doing. On the Free tier, labels with :: are just ordinary labels, and do not mutually exclude each other.
  3. 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 actionEffectTier
/assign me,/assign @bobassignFree
/label ~bug ~"workflow::doing",/unlabel ~bugadd or remove labelsFree
/milestone %v1.0set milestoneFree
/due 2026-12-01,/estimate 2h,/spend 30mdue date, time trackingFree
/relate #2,/confidential,/closelink, confidential, closeFree
/weight 3,/epic &5,/iteration *iteration:"Sprint 1"weight, add to Epic, iterationPremium

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

GitLabGitHubAzure BoardsJira
HierarchyEpic → Issue → TaskIssue + sub-issuesEpic → Feature → User Story → TaskEpic → Story → Sub-task
Board columnlabels / assignee / milestone / iterationProjects Status fieldWork item statusWorkflow state
TimeboxMilestones, iterationsMilestone, Iteration fieldsIteration PathSprint
Common misconceptions① “Board columns are the Issue’s status field”: no, columns are label queries; dragging changes labels. ② “On Free, using the ' 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

Epic &1 “Observability” (group)Premium · sub-Epics require Ultimate Issue #1 add /healthz~type::feature %v1.0 Issue #2 add CI pipeline~type::feature %v1.0 Issue #3 operations runbook~type::docs Task: write testsChild item of an Issue MR !1Description: Closes #1 Milestone %v1.0 (start / due dates)Summarizes completion and burndown for #1, #2 and !1 Closed after merge
Figure 3-1: Epics manage “themes”, milestones manage “time”, and MRs link code to Issues through closing keywords

Flow diagram: data changes when dragging on a board

OpenNo column label workflow::doing workflow::review Closed #1 /healthz remove_labels=workflow::doingadd_labels=workflow::review state_event=close System note“added ~… andremoved ~…”+ notifications / Webhook
Figure 3-2: a board has no status of its own; every change is written back to the Issue itself (so the API, quick actions and the board are equivalent)

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.

Click a card to select it.
$ glab issue list --repo mygroup-lab/myapp

Core commands

CommandPurposeKey parameters
glab issue createCreate Issue-t title,-d description,-l labels,-m milestone,-a assignee,-c confidential,--due-date,-w weight (Premium),-y
glab issue listList Issues-l,-m,-a @me,--closed,--all
glab issue view 1 --commentsView 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 1Edit--label,--unlabel,--milestone
glab label list / createproject labelscan also be used glab api projects/:id/labels
glab api projects/:id/milestones -X POSTCreate 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)

Create labels and milestones: run the label loop and milestone commands from the “Commands” page. Verify: glab label list shows 6 labels.
Create the 3 Issues used in this course:
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.

Advance #1 with quick actions:
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”).

Configure the board: Project → Plan → Issue boards → Create list, then add 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.
(Optional, Premium trial) Create an Epic: Group → Plan → Epics → New epic, titled “Observability”, and add #1 to the Epic. Free users: add a Task “write pytest job” to #2 (Issue page → Child items → Add → Task).
Keep: labels, milestones and Issues are used again in Modules 4 and 7 and in Lesson 2, so do not delete them.
Cost / permissions / risks Cost: 0; requires Planner, Reporter or a higher role; risk: for sensitive information, use -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.

Command-line questions
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"
Scenario analysis
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

▶
GitLab issue boards demo — GitLab
Official channel · English · board columns and Scrum usage (recorded earlier; the interface may differ)
▶
GitLab 201: How to Create an Epic — GitLab Unfiltered
Official Unfiltered channel · English · creating Epics (Premium; Epics became work items in 18.1, so follow the current version’s interface)
▶
GitLab Epics - Setting up your Organization with GitLab (v2) (HD) — GitLab
Official channel · English · organizing cross-project work with Epics
▶
Managing Projects with GitLab | ISSUES, EPICS & MILESTONES — AL HUGHES
Third-party · English · comprehensive demo of Issues, Epics and milestones

Official documentation

Video storyboard (about 75 seconds)

This course material cannot generate video or MP3 directly; the storyboard and narration script are provided.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–75s
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.
or score ≥ 70% on the quiz

Module 4 · Merge Request end to end: review, approval and merge methods

21:00 – 28:00 · The MR is the center of GitLab collaboration: code, discussion, pipelines, approvals, merge checks and Issue closing all converge here
7 minauto-merge · three merge methods: FreeRequired approvals / approval rules: Premium★★★★★
Learning objectives
  • 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.
Prerequisites: Git merge, rebase, squash (Git course); Module 2 roles; Module 3 Issue #1. Importance:★★★★★

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 main are forbidden.
  • Traceability: Issue → MR → commit → pipeline → deployment → environment, one chain.

How: the MR lifecycle

  1. 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.
  2. Prepare (asynchronous): Sidekiq creates the diff, creates the pipeline, checks mergeability, links LFS objects and sends notifications; after that the API field prepared_at gets a value.
  3. Review: assign reviewers (who receive review_requested notifications 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.
  4. 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)”.
  5. 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.
  6. 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.
  7. 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)ResultRequirement
Merge commit (default)Every merge creates a merge commit (even when squashed)No conflicts needed
Merge commit with semi-linear historyStill 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 bubbleThe source branch must be based on the latest commit of the target branch; otherwise rebase first
Fast-forward mergeNo merge commit; the target branch moves forward directly, with fully linear historySame 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_succeeds Deprecated since 17.11; use merge_request.auto_merge.

When: how to choose a merge strategy

Team characteristicsRecommended
Want git log --first-parent main “one line per MR”Merge commit + Squash: Encourage
Need a linear history, convenient git bisectFast-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 MRGitHub PRAzure Repos PR
Merge methodChoose one of three per project + squash policyRepository allows several: merge / squash / rebase, chosen per MRmerge, squash, rebase, semi-linear; can be restricted by branch policy
Auto-mergeauto-mergeauto-mergeauto-complete
Required approvalsPremiumFree (public repos) / paid (private)Branch policy, free
Merge queueMerge trains (Premium)Merge queueNo native support
Common misconceptions① “The Free tier cannot approve”: it can approve; it just cannot “require” approval. ② “Fast-forward merging keeps every commit plus a merge point”: no, it creates no merge commit. ③ “Once auto-merge is set, it always merges”: new commits on the source branch cancel it. ④ “Mentioning an Issue closes it”: it must use a closing keyword and merge into the default branch.

Commit graph: three merge outcomes for the same MR

Merge commit Mfeat/healthz (can be squashed into 1) Semi-linear (rebase first) MThe branch is based on the latest main commit Fast-forward main moves forward directly, no merge commit Squash option is orthogonal to the merge method Merge commit + squash: 1 squash commit + 1 merge commit (2 total) Fast-forward + squash: only 1 squash commit; cleanest history Semi-linear / Fast-forward need a rebase after the target branch moves forward (the MR page has a Rebase button, or the /rebase quick action)
Figure 4-1: the green M is the merge commit; blue ones are commits in the MR

State diagram: common values of detailed_merge_status

preparingunchecked/checking draft_status conflict / need_rebase discussions_not_resolved ci_must_pass / ci_still_running not_approved / requested_changes mergeable Manual merge (requires merge permission on the target branch) auto-merge: merges as soon as checks pass The state only becomes mergeable after each red check is fixed
Figure 4-2: values come from the “Merge status” section of the Merge requests API docs; scripts should read detailed_merge_status, not the deprecated merge_status

Core 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.

Set the scenario, then click “Play”.
$ git push -u origin feat/healthz

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

CommandPurposeKey parameters
glab mr createCreate 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 / diffView--reviewer=@me,--draft,view --comments
glab mr checkout 1Check out MR branch locallyRun tests locally during review
glab mr note 1 -mComment (may include quick actions)/approve /draft /ready /rebase /assign_reviewer @x
glab mr approve 1 / revokeApprove / revoke approvalOn the Free tier approval is optional
glab mr rebase 1Server-side rebasesemi-linear / FF requires it
glab mr merge 1Merge 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)

Configure project merge settings: Project → Settings → Merge requests: set Merge method to Merge commit; set Squash to Encourage; check Enable "Delete source branch" option by default; check Merge checks All threads must be resolved(Pipelines must succeed is left for Lesson 2, since there is no pipeline yet). Save. You can also use the API:
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.

Create a branch and implement the feature:
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
Push and create an MR (Draft):
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”.

Self-review and create a thread: open MR → Changes, in the 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.

Approve and merge:
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).

(Optional) Try fast-forward: change Merge method to Fast-forward merge, then create another small MR (for example, edit the README), push a commit to main before merging, observe that the MR shows it needs a Rebase, and run glab mr rebase N before merging. When done, change the merge method back to Merge commit(Lesson 2 uses this setting).
Keep: the main branch of myapp now contains /healthz, and the Lesson 2 pipeline and the Lesson 3/4 deployment health checks depend on it.
Cost / permissions / risks Cost: 0; requires Maintainer (to merge into protected main); risk: on the Free tier, “approval” does not block merging, so production teams should combine protected branches (only allow merging via MR, forbid direct pushes) with the Lesson 2 rule that “the pipeline must succeed”.

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).

Command-line questions
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
Scenario analysis
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

▶
GitLab 101: Creating a Merge Request — GitLab Unfiltered
Official Unfiltered channel · English · basic steps for creating an MR
▶
038 Gitlab Merge Request Merge Methods — Dan Gitschooldude
Third-party · English · how the three merge methods affect commit history
▶
Issues, Merge Requests and Integrations in GitLab — GitLab
Official channel · English · how Issues and MRs link together (recorded earlier)
▶
GitLab Merge Request | How to Create, Review & Approve Merge Requests in GitLab — Blujay Technologies
Third-party · English · full demo of creating, reviewing and approving

Official documentation

Video storyboard (about 100 seconds)

This course material cannot generate video or MP3 directly; the storyboard and narration script are provided.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–75s
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.
Shot 4 · 75–100s
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.
or score ≥ 70% on the quiz

Module 5 · glab CLI and REST / GraphQL API

28:00 – 35:00 · Almost anything you can do in the UI can be done with the API; glab is a friendly wrapper around the API,glab api is the all-purpose key between the two
7 minglab v1.130.0 · REST v4 · GraphQLProject / group access tokens: Premium required on .com★★★★☆
Learning objectives
  • Use fluently glab the 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.
Prerequisites: HTTP, JSON, and the objects from Modules 2–4. Importance:★★★★☆ (much of the automation in later lessons is built on this)

What: three automation entry points

glabREST API v4GraphQL API
EndpointLocal CLI (calls REST/GraphQL)https://gitlab.com/api/v4/…https://gitlab.com/api/graphql (single endpoint, POST)
Authenticationglab auth login, tokens stored in the system keyringPRIVATE-TOKEN: <token> or Authorization: Bearer <token>Authorization: Bearer <token>; queries require read_api, mutations require api
StrengthsInteractive and friendly, automatically detects the current project,glab api supports placeholders and paginationMost complete coverage, most documentation, easy to use with curlRetrieves multiple levels of nested data in one request; the client selects the fields
Toolsglab --helpdocs.gitlab.com/apiGraphiQL: 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

  1. Project identifier: a numeric ID, or the full URL-encoded path (mygroup-lab%2Fmyapp). In a project directory,glab api supports placeholders :id,:fullpath,:branch,:group,:user etc., automatically filled in from the git remote.
  2. Pagination: default per_page=20, maximum 100; response headers x-next-page,Link (may be omitted when there are many results x-total); some endpoints support more efficient keyset pagination (pagination=keyset). glab api --paginate Automatically paginates.
  3. Methods and parameters: GET to query, POST to create, PUT to update, DELETE to delete. glab api In the -F field syntax, values are converted by type (numbers, booleans, JSON,@file),-f always a string; when field parameters are present, POST is the default.
  4. 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.
  5. 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 headers RateLimit-* and Retry-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 --paginate requires the query to declare $endCursor: String.
  • A field that is null usually means no access; an empty nodes means permission exists but there is no data.

How: token types

TokenPrefixIdentityTier / notes
Personal access token (PAT)glpat-YouFree; if no expiration date is set, it defaults to 365 days, and the default maximum is 365 days
Fine-grained personal access tokenglpat-You, but permissions are limited to specific resources and actions18.10 Beta,19.2 GA, available on Free
Project / group access tokenglpat-Automatically created bot user (project_{id}_bot_…)GitLab.com requires Premium / Ultimate Premium (trial: only 1 allowed); on Self-Managed, any license
Deploy tokengldt-deployment-onlyread-only repository / mirror / packages etc., Free
CI/CD job token—(CI_JOB_TOKEN)running jobInvalid once the job ends (Lesson 2)
Runner authentication tokenglrt-RunnerNew 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/4 id_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

GitLabGitHubAzure DevOps
CLIglabghaz devops / az repos
APIREST v4 + GraphQLREST + GraphQL v4REST (versioned api-version)
Universal callglab apigh apiaz devops invoke / az rest
Common misconceptions① “404 means the project doesn’t exist”: private resources return 404 to users without permission. ② “GraphQL has no rate limiting”: it has complexity, size and timeout limits, and also counts toward Web/API traffic limits. ③ “Using my PAT for bots is the easiest”: when an employee leaves or the token expires, all automation breaks, and permissions are too broad; use project / group access tokens or fine-grained tokens instead.

Architecture diagram: how glab decides “which API to call on which project”

glab mr listCurrent directory ~/gitlablab/myappor -R mygroup-lab/myapp Configuration and credentials~/.config/glab-cli/config.ymlToken → system keyring Parse git remotegit@gitlab.com:mygroup-lab/myapp→ host + :fullpath GET /api/v4/projects/mygroup-lab%2Fmyapp/merge_requests?state=opened&per_page=30Authorization: Bearer glpat-… POST /api/graphqlSome commands use GraphQL internallyglab api graphql -f query=…
Figure 5-1: running glab in a project directory does not require specifying the project; in scripts, use -R or GITLAB_HOST to specify the target explicitly

Comparison chart: request counts for the same report, REST vs GraphQL

REST: 1 + N requests GET …/merge_requests?state=opened GET …/merge_requests/1/approvals GET …/merge_requests/2/approvals … one per MR GraphQL: 1 request project(fullPath:"mygroup-lab/myapp") { mergeRequests(state: opened, first: 50) { nodes { iid title author { username } approved approvedBy { nodes { username } } headPipeline { status } detailedMergeStatus } pageInfo { hasNextPage endCursor } } }
Figure 5-2: the more nested the data, the greater the GraphQL advantage; for simple write operations, REST is more direct

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.

Number of open MRs: 40 Report runs per execution (concurrent scripts): 10
Quota used this minute
0 / 2000
Request statistics
REST 0 · GraphQL 0 · 429 0
Choose a method to run.
$ glab api …

Common glab commands

CommandPurposeNotes
glab auth login / statusSign in / check--hostname self-managed instance; --stdin; --web --device
glab repo create / clone / viewProjectglab repo clone mygroup-lab/myapp; view -w Open browser
glab issue …,glab mr …Issue / MRsee Modules 3 and 4
glab ci status / view / listPipelines (Lesson 2)glab ci view View jobs interactively
glab apiCall any REST / GraphQL endpoint-X -F -f --paginate --output ndjson -i --placeholder
glab config set -g editor vimConfigurationEvery 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)

Prepare data: create two test MRs (one a Draft):
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
REST version (saved as ~/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
GraphQL version (one request):
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.

Cleanup: close and delete the demo MRs and branches:
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>.

Cost / permissions / risks Cost: 0; requires 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.

Command-line questions
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 } }'
Scenario analysis
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

▶
Remote Development - Workspaces CLI Support — GitLab Unfiltered
Official Unfiltered channel · English · demo of the new workspaces subcommand in glab, showing glab’s command style (not an introductory tutorial)

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

Video storyboard (about 80 seconds)

This course material cannot generate video or MP3 directly; the storyboard and narration script are provided.

Shot 1 · 0–20s
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.
Shot 2 · 20–50s
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.
Shot 3 · 50–80s
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.
or score ≥ 70% on the quiz

Module 6 · Protected branches, push rules and CODEOWNERS

35:00 – 42:00 · All protections are enforced on the server: pushes are intercepted by Rails’ access checks before being written to Git, and merges are intercepted by MR merge checks
7 minProtected branches / tags: FreePush rules · CODEOWNERS · group-level protection: Premium★★★★★
Learning objectives
  • In Branch rules for main configure Allowed to merge / Allowed to push and merge / Allowed to force push, and protect release tags.
  • Explain how a single git push push 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.
Prerequisites (not repeated here): Git-side protected branches, approvals, push rules and mirroring operations were covered in Git course Lesson 4(Module 5 “GitLab: projects, protected branches and Merge Requests” and Module 6 “GitLab: approval rules, CODEOWNERS and push rules”), so please review them first. This module approaches them from the platform mechanics and governance perspective, going deeper. Importance:★★★★★

What: three layers of protection

MechanismWhat it protectsWhere it is checkedTier
Protected branchesWho can push, who can merge via MR, whether force pushes are allowed, whether deletion is allowedPush: /internal/allowed access check; merge: at MR merge timeFree (group-level rules Premium)
Protected tagsWho can create / delete matching tags (release tags)Push access checkFree
Push rulesCommit messages, branch names, author email, file name / size, secret files, signed commits, DCOPush access check (per commit)Premium / Ultimate
CODEOWNERSWho must approve MRs that change certain paths; direct pushes to matching paths are rejectedMR approval rules + push checkPremium / 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: 0 No access,30 Developer,40 Maintainer,60 Admin.

How: push rules (Premium; Settings → Repository → Push rules)

CategoryRule
User verificationReject unverified users, reject inconsistent usernames, check whether the commit author is a GitLab user, commit author email regex
Commit messagerequire matching regex, reject matching regex
Branch nameBranch name regex
Prevent accidentsReject unsigned commits, forbid using git push delete tags
FilesBlock pushing secret files, forbidden file name regex, maximum file size
DCOReject 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

GitLabGitHubAzure Repos
Branch protectionProtected branches / Branch rules (Free)Branch protection rules / RulesetsBranch policies
Push content rulesPush rules (Premium)Rulesets push rules (some paid)Some approval policies and Git settings
Code ownersCODEOWNERS + sections + multiple approvals (Premium)CODEOWNERSAutomatically included reviewers
Common misconceptions① “Allowed to merge = Developers means Developers can push directly to main”: no, pushing is controlled by Allowed to push. ② “The higher a CODEOWNERS rule is, the higher its priority”: within the same section, the last matching rule applies. ③ “When several wildcard rules match, the strictest one wins”: the most permissive one wins, so do not use broad wildcard rules that accidentally open main. ④ “Adding CODEOWNERS on Free enforces review”: this needs Premium.

Flow diagram: order of server-side checks for one git push

git pusholdrev newrev ref Shell / Workhorse→ Gitaly receive-pack pre-receive → /api/v4/internal/allowed ① Project access + role (Developer or higher is needed to push)② Protected branches / tags: push and force push③ Push rules (Premium, per commit)④ CODEOWNERS paths (Premium, direct pushes) Update refGitaly write post-receiveSidekiq follow-up If any check fails, the whole push is rejected and the ref is unchanged (atomic) remote: GitLab: You are not allowed to push code to protected branches on this project. remote: GitLab: You are not allowed to force push code to a protected branch on this project. remote: GitLab: Commit message does not follow the pattern '…' (push rule; wording varies slightly by version) ! [remote rejected] main -> main (pre-receive hook declined)
Figure 6-1: checks happen before the ref is updated; a rejected push does not trigger a pipeline and leaves no commits behind

Relationship diagram: CODEOWNERS, approval rules and protected branches

.gitlab/CODEOWNERS * @@maintainer[App] @mygroup-lab/devs/app.py @alice[Infra][2]/Dockerfile @alice @bob^[Docs]*.md @pm MR changes app.py and Dockerfile→ generates Code Owner approval rules main: Require approvalfrom code owners = ON Required: App section 1 person (alice)+ Infra section 2 people (alice, bob)Docs is an optional section and does not block merging Direct push that changes app.py to mainis rejected even with push permission→ must go through an MR
Figure 6-2: CODEOWNERS blocks merging only when “Require approval from code owners” is enabled on the target branch (Premium)

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.

After setting up, click “Push”.
$ git push origin HEAD

Core commands

CommandPurposeNotes
glab api projects/:id/protected_branchesView / create protected branchesPOST: name push_access_level merge_access_level allow_force_push code_owner_approval_required (Premium)
… protected_branches/main -X PATCHModifyWhen changing access levels, “delete and recreate” is commonly used
glab api projects/:id/protected_tagsProtected tagsname=* create_access_level=40
glab api projects/:id/push_rulePush rules (Premium)commit_message_regex branch_name_regex max_file_size prevent_secrets deny_delete_tag
GIT_TRACE=1 git pushDebug pushesView 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)

Apply protection rules: run the “only merge via MR” and “protect all tags” commands from the “Commands” page. On the web, open Settings → Repository → Branch rules, and confirm that main shows Allowed to push and merge: No one.
Verify that direct pushes are rejected:
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
Verify that force pushes are rejected:
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.

Add CODEOWNERS via MR (on Free the file is saved but does not create enforced approvals):
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.

(Optional, Premium trial) Enable Code Owner approval and push rules: in Branch rules, turn on the Require approval from code ownersfor main; run the push rule commands from the “Commands” page; then push a branch named Bad_Name and observe the rejection message. These settings stop working when the trial ends; Lessons 2–4 do not depend on them.
Keep: keep the main protection and tag protection for later lessons (Lesson 2’s protected variables and Lessons 3/4’s OIDC both depend on “main is a protected branch”).
Cost / permissions / risks Cost: 0 (push rules require Premium or a trial); requires Maintainer; risk: for a moment while a protection rule is deleted and recreated, the branch is unprotected; setting Allowed to merge to No one would stop everyone from merging (fix it as an Owner).

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).

Command-line questions
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
Scenario analysis
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

▶
Code Owners - The basics (HD) — GitLab
Official channel · English · the concept of Code Owners and the approval workflow (section syntax follows this lesson and the docs)
▶
How to Setup GitLab Protected Branches, as fast as possible — Latio - Learn Security Together
Third-party · English · quick setup of protected branches
▶
GitLab Approval Rules on Merge Requests — ReleaseTEAM
Third-party · English · approval rules (Premium)
▶
remote: GitLab: You are not allowed to push code to protected branches on this project — The Debug Zone
Third-party · English · troubleshooting the most common errors in this module

Official documentation

Video storyboard (about 80 seconds)

This course material cannot generate video or MP3 directly; the storyboard and narration script are provided.

Shot 1 · 0–25s
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.
Shot 2 · 25–55s
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.
Shot 3 · 55–80s
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.
or score ≥ 70% on the quiz

Module 7 · Wiki, notifications, search and productivity

42:00 – 50:00 · Make knowledge capturable (Wiki), information controllable (notifications and to-dos), content findable (search and references), and work faster (shortcuts and templates)
8 minProject Wiki · notifications · basic search: FreeGroup Wiki · advanced / exact code search: Premium★★★☆☆
Learning objectives
  • 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.
Prerequisites: Module 3 Issues and labels, and Module 4 MRs. Importance:★★★☆☆ (where you save time every day)

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 .md and similar extensions).
  • The default sidebar shows pages by hierarchy and alphabetical order; creating a page named _sidebar can 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 levelMeaning
GlobalUse the setting from the parent level (group / global)
WatchAlmost all activity
ParticipateItems you are involved in (created, commented on, assigned, mentioned, etc.)
On mentionOnly when you are @
DisabledReceive nothing
CustomParticipate + 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

TypeMechanismScopeCharacteristics
Basic search: exact substring matching in the database / GitalyExact substring matching in the database / GitalyFreeCode, commits, comments and Wiki can only be searched within a project; code cannot be searched at group or global scope.
Advanced searchElasticsearch / OpenSearch indexPremiumCode search at group and global scope, with syntax filters
Exact code searchZoekt index, supporting exact and regex modesPremium15.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

SyntaxReferenced objectSyntaxReferenced object
@aliceUser (sends a notification)~bug,~"workflow::review"Label
#123,group/project#123Issue (cross-project)%v1.0,%"release candidate"Milestone
!123Merge Request&123Epic
$123Code snippet9ba12248,a...bCommit / commit range
[[Home]]Wiki page#123+ / #123+sDisplay 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 is Default.md is 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

GitLabGitHubAzure DevOps
WikiProject Wiki (Git repository) + group Wiki (Premium)Repository Wiki (Git repository)Project Wiki or “code as wiki”
Code searchBasic / advanced / exact (Zoekt)Code search (site-wide)Code Search extension
NotificationsInherited by project / group level + to-dosWatch + Notifications inboxSubscription rules
Common misconceptions① “Wiki edits appear in the project’s commit history”: no, it is a separate repository. ② “Free can search code across an entire group”: basic search can only search code within a project. ③ “Setting notifications to Disabled means you won’t miss important items”: you will; use Participate plus the to-do list, and use Custom to turn on “pipeline failed”.

Inheritance diagram: how the notification level is determined

Global defaultWatch Group mygroup-labGlobal → inherits Watch Subgroup platformParticipate Project platform/infraGlobal → effective Participate “Global” means looking up the parent chain for the first non-Global setting; only then does the global default apply Email header X-GitLab-NotificationReason: assigned / review_requested / mentioned / subscribed / own_activity
Figure 7-1 matches the documentation example: global Watch, group Global, subgroup Participate, project Global → the project’s effective level is Participate

Data flow: what a GFM reference triggers

Comment / description / commit message"@bob see #3 and !1" Markdown rendering pipelineReference filter + permission filter #3, !1: generate links + system note “mentioned in …” @bob: to-do + notification (reason: mentioned) Objects the reader cannot view: no link is shown, and the title is not leaked
Figure 7-2: reference rendering is filtered by the reader’s permissions; for a cross-project reference to a private project, readers without permission see only the raw text

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.

Waiting to parse…

Core commands

CommandPurposeNotes
glab api projects/:id/wikis -X POSTCreate Wiki page-f title= -f content=@file -f format=markdown (-F content=@file read from file)
glab api projects/:id/wikis?with_content=1List pagesslug used for updates: PUT …/wikis/:slug
git clone git@gitlab.com:GROUP/PROJECT.wiki.gitClone the Wiki repositoryuse the address shown under Clone repository on the page
glab api projects/:id/notification_settings -X PUTSet the project notification level-f level=participating|watch|global|mention|disabled|custom
glab api projects/:id/searchSearch within the projectscope=blobs|commits|issues|merge_requests|notes|wiki_blobs|milestones search=
glab api todosTo-do listPOST 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)

Create the Runbook page via the API (corresponding to Issue #3):
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.

(Optional) Clone the Wiki repository to edit: On the Wiki page → Wiki actions → Clone repository copy the address (in the form git@gitlab.com:mygroup-lab/myapp.wiki.git), edit locally, Runbook.md and then push git push; the web updates immediately.
Add an MR description template via MR:
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.

Adjust notifications and check to-dos:
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.

Try keyboard shortcuts: on the myapp page, press ? to view the shortcut list; press . to open the Web IDE to browse code (do not commit directly to main — it is protected, and the Web IDE will prompt you to create a new branch).
Cost / permissions / risks Cost: 0; editing the Wiki requires Planner / Developer or higher; risk: do not write passwords or tokens in the Wiki — it is visible to all members who can see the project, and its history is kept permanently in the Wiki repository.

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.

Command-line questions
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
Scenario analysis
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

Video storyboard (about 75 seconds)

This course material cannot generate video or MP3 directly; the storyboard and narration script are provided.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–75s
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.
or score ≥ 70% on the quiz

Module 8 · Collaboration readiness review and troubleshooting basics

50:00 – 60:00 · Turn the first 7 modules into an automatable checklist, and build the troubleshooting habit of “see the error → locate the layer → fix”
10 min12 checks · all can be completed on FreeInteractive troubleshooting tree★★★★★
Learning objectives
  • 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_status and other diagnostic tools.
Prerequisites: Modules 1–7. Importance:★★★★★ (the “acceptance gate” before automation begins in Lesson 2)

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

#CategoryCheck itemHow to checkModule
1PeopleTop-level group enforces 2FAgroups/:id → require_two_factor_authentication2
2PeopleNo more than 3 Maintainers or higher; external members have an expiration dateprojects/:id/members/all2
3PeopleProject is Privateprojects/:id → visibility1, 2
4ProcessDefault branch is main and protecteddefault_branch,protected_branches/main6
5Processmain forbids direct pushes and force pushespush_access_levels= No one,allow_force_push=false6
6ProcessRelease tags are protectedprotected_tags6
7ProcessThreads must be resolved before mergingonly_allow_merge_if_all_discussions_are_resolved4
8ProcessMerge method and squash policy are definedmerge_method,squash_option4
9ProcessCODEOWNERS exists (enable Code Owner approval on Premium)repository/files/.gitlab%2FCODEOWNERS6
10KnowledgeA default MR template exists.gitlab/merge_request_templates/Default.md7
11KnowledgeThe Wiki has a Runbookprojects/:id/wikis7
12PlanningA label system and active milestones existlabels,milestones?state=active3

How: five-layer troubleshooting model

LayerTypical symptomsPreferred diagnostics
① Authentication401,Authentication failed,Permission denied (publickey)glab auth status,ssh -T git@gitlab.com, token expiration date
② Authorization (roles / scopes)403,insufficient_scope, private resources 404members/all/:user_id,personal_access_tokens/self
③ Protection rulesnot allowed to push code to protected branches, push rule rejectionsprotected_branches,push_rule,GIT_TRACE=1
④ Tier / deployment modelSetting does not exist, quick action has no effect, API 404Tier / Offering at the top of the docs,namespaces of the plan
⑤ Object stateMR cannot be merged, Issue not closed, auto-merge canceleddetailed_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

GitLabGitHubAzure DevOps
Built-in compliance viewCompliance center (Ultimate)Rulesets insights, security overviewBranch policy report
Free alternativeThis module’s API scriptgh api Scriptaz repos policy list
Common misconceptions① “One review is enough”: configuration drifts (someone temporarily loosens protection and forgets to revert it), so it should run automatically on a schedule. ② “Every 404 means the path is wrong”: it can also mean no permission. ③ “A failed push is a network problem”: check the 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

① AuthenticationWho are you? 401 ② AuthorizationRole / scope? 403/404 ③ Protection rulespre-receive declined ④ TierFree / Premium? ⑤ StateDraft / conflicts / checks glab auth statusssh -T git@gitlab.comToken expired / revokedAfter 2FA, HTTPS needs a PAT members/all/:uidtokens/self scopesPrivate resources return 404Inherited roles cannot be lowered protected_branchesprotected_tagspush_ruleCODEOWNERS Docs Tier / Offeringnamespaces → plan.com has no InternalFree: 5 users, then read-only detailed_merge_statusSystem notesProject settings
Figure 8-1: rule out layers from left to right; when an earlier layer has not been passed, the symptoms of a later layer are often misleading

Readiness radar: four dimensions

People (2FA, members, visibility) Process (protection, merge settings) Knowledge (templates, Runbook) Planning (labels, milestones)
Figure 8-2: after the integrated lab is complete, all four dimensions of myapp should be close to full marks (green area)

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.

$ python3 gitlab_ready.py mygroup-lab/myapp

Quick reference for diagnostic commands

CommandPurposeWhat to look for
GIT_TRACE=1 GIT_SSH_COMMAND="ssh -v" git pushPush failsthe key used,remote: GitLab: message
GIT_CURL_VERBOSE=1 GIT_TRACE=1 git fetchHTTPS authentication issue401 / 403, credential helper
glab auth statusCLI sign-in statushost, protocol, whether the token is valid
glab api -i …API errorstatus code,RateLimit-*, error JSON
GLAB_DEBUG_HTTP=1 glab mr listglab behaves unexpectedlythe requests actually sent
glab api personal_access_tokens/selfToken informationscopes,expires_at,active
glab api projects/:id/members/all/:uida person’s effective roleaccess_level
glab api projects/:id/merge_requests/:iidWhy an MR cannot be mergeddetailed_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)

Save the review script ~/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)
Run review:
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
Create configuration drift and let the script detect it:
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
Practice with the troubleshooting tree: open the interactive troubleshooting tree on this module’s “Troubleshooting” page, choose “Push rejected → remote: GitLab: … protected branches”, and compare it with the output you saw in the Module 6 lab.
Keep: in Lesson 2 the script will be extended with CI-related checks (“the pipeline must succeed”, runner availability).
Cost / permissions / risks Cost: 0; the script is read-only (the drift demo step modifies and then restores a setting); reading the group 2FA setting requires a group Owner; risk: do not store tokens in plain text on shared machines; glab uses the system keyring by default.

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.

Command-line questions
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"])'
Scenario analysis
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

▶
remote: GitLab: You are not allowed to push code to protected branches on this project — The Debug Zone
Third-party · English · troubleshooting the most common push errors (corresponds to layer ③ of the five-layer model)
▶
GitLab CI CD Tutorial for Beginners [Crash Course] — TechWorld with Nana
English · preview material for Lesson 2: introduction to pipelines and runners

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.

Shot 1 · 0–25s
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.
Shot 2 · 25–60s
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.
Shot 3 · 60–90s
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.
or score ≥ 70% on the quiz

Command cheat sheet

The glab, API, push options, quick actions and settings paths used in Hour 1
glab v1.130.0GitLab.com

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 date

Protection 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

ScenarioSyntax
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 IssueCloses #1 / Fixes / Resolves / Implements (merge into default branch)

Quick troubleshooting table

SymptomMost likely causeFirst command
Permission denied (publickey)SSH key not added / wrong key usedssh -vT git@gitlab.com
HTTP Basic: Access deniedPassword used after 2FA; PAT expiredglab auth status
not allowed to push code to protected branchesmain is protectedglab api projects/:id/protected_branches
401 UnauthorizedNot authenticated / token invalidglab api personal_access_tokens/self
403 insufficient_scopeInsufficient scopeSame as above; check scopes
404 Project Not FoundNo permission or path not encodedglab api projects/mygroup-lab%2Fmyapp
MR cannot be mergedDraft / conflicts / threads / approvals / rebase neededdetailed_merge_status
Issue did not close automaticallykeyword, target branch, project settingsglab api projects/:id → autoclose_referenced_issues
Setting cannot be foundTier / role / deployment modelTier / Offering at the top of the docs

Recommended baseline configuration (myapp)

LocationSetting
Group → Settings → General → PermissionsEnforce 2FA; Roles allowed to create projects = Maintainer
Project → Settings → GeneralVisibility = Private
Project → Settings → Merge requestsMerge commit (or FF); Squash = Encourage; delete source branch by default; all threads must be resolved; (Lesson 2) pipeline must succeed
Project → Settings → Repository → Branch rulesmain: 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
WikiRunbook page

Integrated lab + final quiz

Build a “collaboration-ready” myapp from scratch: groups, permissions, planning, the MR workflow, protection rules and a knowledge base, and accept it with the readiness script. This is exactly the starting point for Lesson 2’s CI/CD
After class ≈ 30 minutesCombining all modules
Scenario You are the technical lead of a new team. The team will develop myapp (Flask + gunicorn + Redis, port 5000) on GitLab.com. Requirements: only group members can see the code; every change must be merged into main via MR; each MR is linked to an Issue that closes automatically after merging; release tags can only be created by Maintainers; the team has unified labels, milestones, MR templates and a Runbook; and all of this configuration can be accepted by a script. If you have already completed the labs in Modules 1–8, you can start directly from Step 5; or you can redo everything in a new project mygroup-lab/myapp-final from scratch (delete it when finished, and keep myapp for Lesson 2).
Prerequisite checks (Modules 0, 1)
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"))'
(when redoing) create the project and push the initial code (Module 2)
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 main
Planning system (Module 3): create 6 labels and the milestone v1.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 -y
Protection rules and merge settings (Modules 4, 6)
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
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
Deliver the feature, CODEOWNERS and MR template together in one MR (Modules 4, 6, 7)
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).

Review, resolve threads, merge, and verify that the Issue closes (Module 4): add a comment thread in the MR → query 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.
Runbook and notifications (Module 7): use 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.
Acceptance (Module 8):
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”.

Acceptance checklist

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

Verification basis for all technical facts in this lesson (verified: 2026-11-16)
TopicVerified findingSource (accessed 2026-11-16)
GitLab versions and cadenceA 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)
glabv1.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 keyringgitlab-org/cli releases · glab auth login · glab api
Deployment modelsDedicated: single-tenant, GitLab-hosted, AWS (Azure/GCP not supported), customer-selected region, customer-owned KMS can be used, UltimateGitLab Dedicated
Tiers and pricingFree $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-onlyPricing · 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 hoursHosted runners on Linux
RolesMinimal 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 groupsRoles and permissions · Members API · Custom roles
GroupsSubgroups 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 visibilitySubgroups · Groups API · Project and group visibility
PlanningEpic: 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 rulesEpics · Labels · Issue boards · Closing issues
MRThree 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 valuesMerge methods · Auto-merge · Approval settings · MR API · Push options
API and tokensGraphQL 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 PremiumGraphQL · Rate limits · PAT · Fine-grained PAT · Project access tokens
ProtectionProtected 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 / @@roleProtected branches · Push rules · Code Owners · CODEOWNERS syntax
ProductivityWiki 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.mdWiki · 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.1 etc.), and the base image is python:3.13-slim; Lesson 2 will pin the versions in CI.