Boxes crossing 5 stepping stones from an old brick workshop to a modern building
DevOps Engineering

Jenkins to GitLab Migration: Plan, Pitfalls and CI Examples

A 5-stage plan to move from Jenkins and Gerrit to GitLab CI/CD, what breaks, and Jenkinsfile to YAML examples.

Radoslaw Malec

29 min read

Bottom line

A Jenkins to GitLab migration runs in 5 stages. The old source control system (Gerrit or SVN) stays the source of truth until cutover day, and Jenkins and GitLab build the same commits side by side before anything is switched off.

StageHow longDone when
1. Preparation4 to 8 weeksJobs inventoried, repositories mirrored, first pipelines green
2. User acceptance2 to 4 weeksJenkins and GitLab agree on the same commits
3. Cutover1 day per repository groupOld SCM is read-only, Jenkins jobs are disabled
4. Verify and test1 to 3 daysBranch, merge request, tag and scheduled pipelines are green
5. Post-cutover2 weeksSign-off, Jenkins configuration archived
The 5 stages of a Jenkins to GitLab migration: preparation, user acceptance, cutover, verify and test, post-cutover
The old SCM is the source of truth through stages 1 and 2. GitLab takes over at cutover.

3 things decide how it goes:

  1. The YAML is the easy part. Migrations fail on state that never lived in a Jenkinsfile: controller configuration, what is installed on the agents, and every script, webhook and badge that calls Jenkins
  2. Translate the logic of each job. The check, post-merge, nightly and deploy jobs of 1 repository become 1 .gitlab-ci.yml, and rules: decides which jobs run for which event
  3. Run both systems on the same commits before cutover. A repository is ready when Jenkins and GitLab agree on pass or fail, test counts and artifacts for the last N builds

The 6 translations you will write most often:

JenkinsGitLab CI/CD
agent { label 'linux' }tags: [linux]
steps { sh 'make build' }script: - make build
when { branch 'main' }rules: - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
withCredentials([...])A masked CI/CD variable, or secrets:
junit 'reports/*.xml'artifacts: reports: junit: reports/*.xml
triggers { cron(...) }A pipeline schedule, created in the UI or through the API

The full Jenkinsfile to GitLab CI cheat sheet is further down. If an AI agent does the translation, give it the jenkins2gitlab skill file: a Markdown file with the mapping tables, the pitfalls and the validation steps from this guide.

The guide assumes a typical legacy stack: code in Gerrit (with some older code in SVN), pipelines in Jenkins, plus Jira, an artifact repository, Vault and a GitOps tool. "Old SCM" means Gerrit, SVN or both. The target is 1 GitLab instance that holds code, pipelines and documentation. Keywords, defaults and tiers were checked against the GitLab 19.6 documentation.

Planning a Jenkins to GitLab migration, or stuck in the middle of one? Get a free DevOps assessment: a senior engineer reviews your CI/CD, infra, Kubernetes, cloud cost and on-call setup.

Find your situation:

Jenkins vs GitLab CI: what changes in a migration

Jenkins runs pipelines against code that is stored somewhere else. A GitLab project holds the code, the pipeline, the merge requests and the documentation, so several things that were separate systems become settings of 1 project.

ConcernJenkinsGitLab CI/CD
Pipeline definitionJenkinsfile (Groovy), Job DSL, or config.xml on the controller.gitlab-ci.yml in the repository
Jobs for 1 repositorySeveral jobs: check, post-merge, nightly, deploy1 file, with rules: per job
Where jobs runAgents selected by label expressions (AND and OR)Runners selected by tags (AND only)
ReuseShared librariesCI/CD components and include:
SecretsCredentials store on the controllerCI/CD variables, Vault, or OpenID Connect (OIDC) tokens
IntegrationsPluginsMostly built in
Code review gateGerrit Trigger and the Verified voteMerge request pipelines and "Pipelines must succeed"
Access controlSecurity matrix, plus SCM permissions kept in syncRoles on groups and subgroups, inherited downwards
Scheduled runscron in the JenkinsfilePipeline schedules, stored outside the YAML
Warning resultUNSTABLE (yellow)No such state: allow_failure: exit_codes:

The new pipelines do not have to copy the Jenkins jobs. They have to run the same logic for the same purpose. Prefer the GitLab feature over an emulation of the Jenkins one. For the general picture of stages, runners and artifacts, see the CI/CD pipeline guide.

Check your GitLab tier before you plan

Several features in this guide need a paid GitLab tier, and that changes design decisions early. Check the GitLab feature comparison against this list before the plan is written:

TierFeatures this guide uses
PremiumPush rules. Required approvals, multiple approval rules and Code Owners. Specific users or bots in "Allowed to push". Merge trains. Protected environments with deployment approvals. The secrets: keyword for Vault. needs:project. Environment-scoped group variables. Epics. LDAP group sync, SAML group links and SCIM provisioning
UltimateCustom roles

Each section below gives the Free tier alternative where one exists.

What breaks in a Jenkins to GitLab migration

Most failures come from implicit state: what lived in the Jenkins controller, on the agents, and in everything that quietly called Jenkins. 11 symptoms to expect:

SymptomCauseFix
Jobs stay pending foreverJenkins label expressions allow OR. GitLab tags are AND onlyAdd 1 shared tag to every runner in both pools
Secrets are missing or uselessEncrypted values copied from config.xmlKeep the credential IDs only and recreate each value from its real source
Jobs run too often, or neverGerrit Trigger filters do not map 1 to 1 to rules: changes:Rebuild the filters with rules: and compare runs during the parallel phase
Builds are suddenly slowPersistent Jenkins workspaces are replaced by clean containersDesign cache: and bake tools into the job image
Version scripts breakGitLab clones shallow by default (depth 20 for new projects)Set GIT_DEPTH: 0 on jobs that read history
Logs are truncatedThe runner output_limit defaults to 4096 KB (4 MB)Raise output_limit in the runner config.toml
Artifacts are rejectedMaximum artifact size (100 MB by default on self-managed)Raise the limit, or publish to a package registry
Cross-project access is deniedThe CI/CD job token allowlistAdd the calling project to the target project's allowlist
Remote triggers and badges are deadScripts, webhooks and READMEs still point at Jenkins URLsList inbound callers in the inventory and repoint each one
Coordinated multi-repository changesGerrit topics have no direct equivalentMulti-project pipelines or coordinated merge requests
Dynamic parameters, unusual pluginsNo GitLab counterpartStatic options, or a script that generates a child pipeline

The label expression that leaves jobs pending

A Jenkins agent label can say "linux, and either pool":

agent { label 'linux && (build || build-prod)' }

A naive translation lists every label as a tag:

tags: [linux, build, build-prod]

A GitLab job only runs on a runner that has all of its tags. No runner carries both build and build-prod, so the job waits forever. Give the runners of both pools 1 shared tag and use that:

tags: [linux-build]
Jenkins label expressions allow AND and OR, GitLab runner tags are AND only, so a job that lists every label as a tag stays pending
Why a translated job stays pending, and the fix.

The secrets that cannot be copied

Values such as {AQAAABAAAAAQ...} in config.xml and credentials.xml are encrypted with the old controller's key. They are useless anywhere else, and copying them into a repository leaks them for nothing. Export the credential IDs only, and recreate each secret from where it really comes from.

The 5-stage Jenkins to GitLab migration plan

The order matters more than the durations: the old SCM stays the source of truth through stages 1 and 2, and GitLab takes over in stage 3.

Stage 1: preparation (4 to 8 weeks)

The old SCM is the source of truth.

  • Inventory first. Export the Jenkins jobs with their triggers, agent labels, last run date and owner, plus plugins, shared libraries and credential IDs. Also list inbound callers: remote trigger URLs, scripts that call the Jenkins API, webhooks and build badges. This list is the migration backlog
  • Prune before you migrate. Delete the jobs that have not run in 90 days or that nobody owns. This is often the biggest cut in scope
  • Design the group structure. It should reflect how the organisation owns code. GitLab's guide to organizational hierarchies is a good start
  • Mirror the old repositories. See repository mirroring and the 3 notes below
  • Configure the project settings. Protected branches, merge request checks (pipelines must succeed, resolved threads, approvals), the merge method, and push rules that match the old submit policies
  • Develop and test .gitlab-ci.yml, with the shared configuration and the cross-project dependencies. A job that clones another project or downloads its artifacts needs that project's CI/CD job token allowlist to allow it

Mirroring, per source:

  • Gerrit: add GitLab as a remote in the Gerrit replication plugin configuration, with the refspecs +refs/heads/*:refs/heads/* and +refs/tags/*:refs/tags/*. This leaves out refs/changes/* and refs/meta/*. The default branch name in GitLab is main
  • SVN: convert with git svn and an authors file, or use an SVN to Git bridge, and sync on a schedule. Expect non-standard layouts, svn:externals (they become submodules or build steps), svn:ignore (it becomes .gitignore) and large binaries
  • Protect the mirrored branches so that only the mirror can push, and the 2 sides cannot drift. On any tier, from GitLab 18.10, set "Allowed to push and merge" to the mirror's deploy key. On Premium, the mirror's user or service account also works

Stage 2: user acceptance (2 to 4 weeks)

Developers get used to code, pipelines and documentation in 1 place while they still submit through Gerrit or SVN. The old SCM stays the source of truth and mirroring keeps running.

  • Post-merge comparison. Jenkins and GitLab build the same mirrored commits. Compare tests, pass or fail, duration and artifacts
  • Pre-merge preview. Replication does not carry unmerged Gerrit patch sets, so developers also push feature branches to GitLab and open merge requests to try the pipelines and the review flow. Mirrored branches stay writable only by the mirror

Keep a scoreboard per repository of Jenkins and GitLab results for the last N builds. When they agree consistently, the repository is ready for cutover.

What a parallel run catches. One product team with about 300 Jenkins jobs ran both systems for 3 weeks. 11 test jobs were red in GitLab and yellow in Jenkins: the Jenkins jobs ignored the test exit code (|| true), and the junit step only marked the build UNSTABLE. Nobody looked at yellow builds anymore. The translated jobs surfaced the failures, and the hidden debt had to be paid.

GitLab has no "unstable" state. Where a warning result is needed, have the script exit with a dedicated code and declare it:

test:
  script:
    - make test || exit 3
  allow_failure:
    exit_codes: [3]
  artifacts:
    when: always
    expire_in: 2 weeks
    reports:
      junit: reports/*.xml

Stage 3: cutover (1 day per repository group)

GitLab becomes the source of truth. The stage is done when the old SCM is read-only and the Jenkins jobs are disabled.

  1. Freeze merges in the old SCM
  2. Run a final mirror sync and verify that branch heads and tags match on both sides
  3. Disable the replication from Gerrit to GitLab, or stop the SVN sync job. Otherwise the next Gerrit event may overwrite GitLab
  4. Make the old SCM read-only. In Gerrit, remove Push, Submit and Create Reference from the developer groups. Keep a mirror account (it is what pushes commits back if you roll back) with Push, Push Merge Commit, Forge Author and Forge Committer on refs/heads/*, and Create Reference and Create Annotated Tag on refs/tags/*. In SVN, reject writes with a pre-commit hook or access rules
  5. Disable the Jenkins jobs and keep them: java -jar jenkins-cli.jar -s JENKINS_URL disable-job JOB_NAME, or disabled(true) in Job DSL
  6. Change the branch protection in GitLab. Set "Allowed to push" to "No one", so every change to a protected branch such as main goes through a merge request with pipelines, and set "Allowed to merge" to Maintainers or Developers

Stage 4: verify and test (cutover day plus 1 to 3 days)

  • Pipelines on main are green
  • Merge request pipelines are green, and they block merging when they fail
  • Tag pipelines run and produce the same release output as before
  • All pipeline schedules exist and have run at least once (the API call to create one is below)
  • Artifacts land in the right place (package registry, artifact repository, container registry) with the expected names and versions
  • Integrations work end to end: Jira links, Vault access, GitOps deployment, notifications
  • Inbound callers from the inventory point at GitLab: trigger API, badges, webhooks

Stage 5: post-cutover (2 weeks)

  • Check pipeline health daily: failure rate, queue time and duration against the Jenkins baseline. Some difference is fine, a big slowdown is a finding
  • Keep the Jenkins jobs disabled and in place
  • Collect developer feedback and resolve it first in, first out
  • Decide which Gerrit metadata to keep. Review comments, owner and topic changes and edit history are not migrated. They live in refs/changes/*/meta
  • After sign-off, archive the Jenkins configuration and disable the Jenkins and Gerrit accounts. The migration is complete

Agree on a rollback plan before cutover

Agree on the rollback triggers before cutover day, for example "a release is blocked for more than 1 working day" or "a critical pipeline is red with no fix in sight". A rollback is 6 steps:

  1. Freeze merges in GitLab
  2. Bring back the commits made in GitLab since cutover, then disable the push mirror
  3. Make the old SCM writable again
  4. Restore the mirror direction: turn the Gerrit to GitLab replication back on, and the mirror-only branch protection in GitLab
  5. Turn the Jenkins jobs back on
  6. Announce the rollback, fix the root cause, and schedule a new cutover

A full rollback is rare. It is one more reason to cut over in repository groups: a rollback then covers 1 group and the rest keep moving.

Translate a Jenkinsfile to .gitlab-ci.yml

Jenkins pipeline configuration lives in 1 of 2 places: in Git (Jenkinsfiles, or Job DSL scripts applied by a seed job), or, for jobs configured in the UI, only in config.xml on the controller. The hard case is a full config.xml stored in Git and changed through Groovy init hook scripts, where fixing a typo in a job description becomes a 200-line patch script.

Either way, get every pipeline definition into files before translating. Jenkinsfiles and Job DSL are ready to use. For jobs configured in the UI, a short script against the Jenkins REST API (or jenkinsapi) fetches config.xml, triggers and labels:

curl --netrc  "https://your.jenkins.com/job/folder/job/my-job/config.xml" -o my-job.config.xml

The keyword mapping

A pipeline has the same parts in both tools: input parameters, environment, where jobs run, stages, steps and artifacts.

Jenkins (declarative)GitLab CI/CD
parameters { choice(name: 'TARGET_ENV', ...) }spec: inputs: target_env: options: [...] (docs)
environment { APP_NAME = 'billing-api' }variables: APP_NAME: billing-api
options { timeout(time: 30, unit: 'MINUTES') }timeout: 30m on each job
options { disableConcurrentBuilds() }resource_group: on the deploy job
agent { label 'linux && docker' }tags: [linux-docker] (1 combined tag here. tags: [linux, docker] also works when the runners carry both)
stages { stage('Build') { ... } }stages: [build, ...] and stage: build per job
steps { sh 'make build' } (freestyle: "Execute shell")script: - make build
when { branch 'main' }rules: - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $CI_PIPELINE_SOURCE == "push"
withCredentials([string(...)])A CI/CD variable, or secrets:
junit 'reports/*.xml'artifacts: reports: junit: reports/*.xml
archiveArtifacts artifacts: 'dist/**'artifacts: paths: [dist/]

The same pipeline in both tools

The numbers in the comments match across the 2 files. First the Jenkinsfile:

pipeline {
  agent { label 'linux && docker' }                         // [3] where jobs run

  parameters {                                              // [1] input parameters
    choice(name: 'TARGET_ENV', choices: ['staging', 'production'])
  }

  environment {                                             // [2] environment
    APP_NAME = 'billing-api'
  }

  options {                                                 // [2] options
    timeout(time: 30, unit: 'MINUTES')
    disableConcurrentBuilds()
  }

  stages {                                                  // [4] stages
    stage('Build') {
      steps { sh 'make build' }                             // [5] steps
    }
    stage('Test') {
      steps { sh 'make test' }
      post { always { junit 'reports/*.xml' } }             // [6] reports
    }
    stage('Deploy') {
      when { branch 'main' }
      steps {
        withCredentials([string(credentialsId: 'deploy-token', variable: 'DEPLOY_TOKEN')]) {
          sh './deploy.sh "$TARGET_ENV"'
        }
      }
    }
  }

  post {
    success { archiveArtifacts artifacts: 'dist/**' }      // [6] artifacts
  }
}

And the equivalent .gitlab-ci.yml:

spec:                                         # [1] parameters -> spec:inputs
  inputs:
    target_env:
      options: [staging, production]
      default: staging
---
variables:                                    # [2] environment -> variables
  APP_NAME: billing-api
  TARGET_ENV: $[[ inputs.target_env ]]

default:
  image: registry.example.com/build/toolchain:1.4
  tags: [linux-docker]                        # [3] agent label -> tags

workflow:
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
    - if: $CI_COMMIT_TAG
    - if: $CI_PIPELINE_SOURCE =~ /^(web|schedule|api|trigger|pipeline)$/
    - if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
      when: never                             # avoid duplicate branch + MR pipelines
    - if: $CI_COMMIT_BRANCH

stages: [build, test, deploy]            # [4] stages

build:
  stage: build
  timeout: 30m                                # [2] options { timeout }
  script:                                     # [5] steps -> script
    - make build
  artifacts:                                  # [6] archiveArtifacts -> artifacts
    paths: [dist/]
    expire_in: 2 weeks

test:
  stage: test
  timeout: 30m
  script: make test
  artifacts:
    when: always                              # [6] post { always { junit } }
    expire_in: 2 weeks
    reports:
      junit: reports/*.xml

deploy:
  stage: deploy
  timeout: 30m
  rules:                                      # when { branch 'main' }, pushes only
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $CI_PIPELINE_SOURCE == "push"
  environment: $TARGET_ENV
  resource_group: $TARGET_ENV                 # [2] disableConcurrentBuilds() -> resource_group
  script:
    - ./deploy.sh "$TARGET_ENV"               # DEPLOY_TOKEN comes from a CI/CD variable

6 things to take from the translation:

  • Pipeline-level spec: inputs needs GitLab 17.11 or later. It is the closest match to "Build with Parameters" in Jenkins. On older versions, use variables: with a description
  • workflow: rules decides which pipelines exist at all. Once any job has a merge request rule, a push to a branch with an open merge request creates 2 pipelines without it. With a version that is too simple, manual, scheduled or tag pipelines disappear
  • A branch rule alone also matches scheduled, manual and API pipelines on that branch. The deploy job adds $CI_PIPELINE_SOURCE == "push", so the nightly schedule on main does not deploy
  • timeout: goes on each job. default: timeout arrived in GitLab 19.6 behind a feature flag that is off by default
  • Credentials leave the file. withCredentials becomes a CI/CD variable or a secret fetched at runtime
  • Cron triggers are not stored in YAML. triggers { cron(...) } becomes a pipeline schedule, configured in the UI or through the API

Creating a schedule through the API:

curl --request POST \
  --header "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \
  --form "description=Nightly E2E build" \
  --form "ref=refs/heads/main" \
  --form "cron=0 2 * * *" \
  --form "cron_timezone=UTC" \
  --form "active=true" \
  "https://gitlab.example.com/api/v4/projects/org%2Fpayments%2Fbilling-api/pipeline_schedules"

Translate Jenkins pipelines at scale with an AI agent

LLMs write YAML well, and they spare you the indentation hunt described in the YAML document from hell. They cannot guess how your organisation uses Jenkins. 2 steps close that gap:

  1. Write 1 reference pipeline by hand. It is your golden path, and it copies no single Jenkins job: every plugin replacement and pattern you want (inputs, components, secrets, reports, deployment rules), used the way your projects use them
  2. Add the controller context. A config.xml lacks the global configuration, the plugin defaults, the environment injected by agents and the shared library code. Export the plugins, the nodes and labels, the credential IDs and the global environment variables along with the jobs

The jenkins2gitlab skill file packages these rules for an AI agent. It covers 7 steps: discover the job definitions, export the controller context, classify each job, translate, harden, validate and report. The rules it enforces are the pitfalls from this guide:

  • Never copy an encrypted Jenkins secret, and never write a secret value into YAML, notes or logs
  • Never turn label 'a || b' into tags: [a, b]
  • Never invent a runner tag: every tag is checked against a real, online runner
  • Always add expire_in to artifacts, and when: always to test reports
  • Always mark what cannot be mapped as a TODO(migration) for a human decision
  • Validate every generated file with the GitLab CI lint API before reporting

Turn Jenkins shared libraries into CI/CD components

Jenkins shared libraries usually mix reusable pipeline structure with Groovy logic. In GitLab the 2 split:

Shared library partGitLab equivalent
Pipeline templates (vars/*.groovy)CI/CD components, or include: project templates
Library parametersComponent inputs
@Library('ci-lib@v2') pinningA component version
Global values the library injectedGroup-level CI/CD variables
Groovy classes (src/**)Scripts in a versioned tools image

A Jenkins library call such as:

@Library('ci-lib@v2') _
standardBuild(goVersion: '1.22', runnerTag: 'linux-docker')

becomes a component in a shared project, for example org/platform/ci-components/templates/go-build.yml:

spec:
  inputs:
    stage:
      default: build
    go_version:
      default: "1.23"
    runner_tag:
      default: linux-docker
---
go-build:
  stage: $[[ inputs.stage ]]
  image: registry.example.com/mirror/golang:$[[ inputs.go_version ]]
  tags: ["$[[ inputs.runner_tag ]]"]
  script:
    - go build ./...
    - go test ./... -coverprofile=coverage.out

Each project then uses it with a few lines:

include:
  - component: $CI_SERVER_FQDN/org/platform/ci-components/go-build@1.2.0
    inputs:
      go_version: "1.22"

@1.2.0 needs a Git tag 1.2.0 in the component project. A release is only needed to publish the version in the CI/CD Catalog. Pin a version in production pipelines and keep @main for testing the component itself.

One GitLab project replaces many Jenkins jobs

In GitLab, 1 project handles every trigger in a single .gitlab-ci.yml. The link between an event and a job is written with rules:, when: and changes:.

Four separate Jenkins jobs become one .gitlab-ci.yml where rules decide which job runs for which event
Several Jenkins jobs for 1 repository become 1 file with rules.

Verification and post-merge jobs:

stages: [verify, build, test, deploy]

# Check job: every merge request (replaces patchset-created + Verified vote)
lint:
  stage: verify
  script: make lint
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"

# Post-merge job: release branches, only when firmware changed
# (replaces Gerrit Trigger branch + file path filters)
build-firmware:
  stage: build
  script: make firmware
  rules:
    - if: $CI_COMMIT_BRANCH =~ /^release\//
      changes:
        - firmware/**/*

# Nightly job: pipeline schedule (replaces Jenkins cron trigger)
nightly-e2e:
  stage: test
  script: make e2e
  rules:
    - if: $CI_PIPELINE_SOURCE == "schedule"

On branch pipelines, changes: compares with the previous commit. It is always true for new branches, tags, schedules and pipelines started manually or through the API, so the job can run more often than the Jenkins original. Add compare_to: only when there is a stable base to compare with.

Deployment and GitOps jobs:

# Pre-merge deployment: manual, per merge request
deploy-review:
  stage: deploy
  script: ./deploy.sh "review-$CI_MERGE_REQUEST_IID"
  environment:
    name: review/$CI_MERGE_REQUEST_IID
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      when: manual
      allow_failure: true

# GitOps hand-off: bump the image tag in the config repo watched by the GitOps tool
update-gitops:
  stage: deploy
  image: registry.example.com/tools/gitops:1.0   # contains git and yq
  resource_group: gitops                          # avoid concurrent pushes
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $CI_PIPELINE_SOURCE == "push"
  script:
    - git config --global user.name  "gitops-bot"
    - git config --global user.email "gitops-bot@example.com"
    # clone outside the build directory so .git/config is not cached; the job token expires with the job
    - git clone "https://gitlab-ci-token:${CI_JOB_TOKEN}@${CI_SERVER_FQDN}/org/payments/deploy-config.git" /tmp/deploy-config
    - cd /tmp/deploy-config
    - yq -i ".image.tag = \"${CI_COMMIT_SHORT_SHA}\"" apps/billing-api/values.yaml
    - git diff --quiet || (git commit -am "billing-api ${CI_COMMIT_SHORT_SHA}" && git push)

The GitOps job pushes with the short-lived CI/CD job token, so no long-lived token is stored (generally available since GitLab 19.1). It needs 3 things on the target project: "Allow Git push requests to the repository" enabled, this project on its job token allowlist with read and write access to repositories, and at least the Developer role there for the user who started the pipeline. A push with a job token starts no pipeline in the target project. On older versions, use a project access token with the write_repository scope in a masked variable.

Move access control from the security matrix to groups

In Jenkins, access is managed with the security matrix (or a role-based plugin), optionally fed by LDAP groups. The same groups must also be kept in sync with the Gerrit or SVN permissions: 2 systems, 2 permission models, constant drift.

In GitLab the organisation is modelled as groups and subgroups. Access is granted by assigning a role to a user or a group at a given level, and it is inherited downwards:

org/                       (top-level group)
โ”œโ”€โ”€ platform/               (Platform team: Maintainer)
โ”‚   โ”œโ”€โ”€ ci-components
โ”‚   โ””โ”€โ”€ runners-config
โ”œโ”€โ”€ payments/               (Payments team: Developer)
โ”‚   โ”œโ”€โ”€ billing-api
โ”‚   โ””โ”€โ”€ invoicing
โ””โ”€โ”€ legacy/                 (read-only archive of SVN imports)

Drive membership from the identity provider so nobody manages it by hand (Premium):

  • LDAP group sync (Self-Managed) with OpenLDAP or Active Directory. The LDAP integration itself is on the Free tier
  • SAML group links with Microsoft Entra ID (formerly Azure AD), Keycloak, or any other SAML 2.0 identity provider
  • SCIM provisioning to create and deactivate accounts when people join or leave

A runner admin role with no project membership

Beyond the standard roles, GitLab has custom roles (Ultimate). A useful one is a runners admin: a low base role such as Minimal Access or Guest, plus the permissions to view and manage runners, assigned at the top-level group. On GitLab Self-Managed the call needs an administrator token and the role exists for the whole instance:

curl --request POST \
  --header "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \
  --header "Content-Type: application/json" \
  "https://gitlab.example.com/api/v4/member_roles" \
  --data '{
    "name": "Runner admin",
    "description": "Can view and manage runners only",
    "base_access_level": 10,
    "read_runners": true,
    "admin_runners": true
  }'

On GitLab.com the endpoint is POST /groups/:id/member_roles, called by a group Owner.

Custom roles only add permissions to their base role, so a low base role is the closest match to "Owner, but only for runners". The infrastructure team can configure and pause runners for the whole organisation without being a member of any project. Treat the role as privileged: a runner sees the code and the variables of every job it runs.

Replace Jenkins credentials with variables, Vault or OIDC

Jenkins credentials have 3 usual replacements in GitLab. They are listed from the simplest to the one that stores nothing.

OptionWhere the secret livesTier
1. CI/CD variableIn GitLab, masked and protectedFree
2. Vault through OIDCIn Vault, fetched at runtimePremium for secrets:, Free with the Vault CLI
3. Direct OIDC federationNowhere: the target trusts GitLab's tokenFree
Three replacements for Jenkins credentials in GitLab: a CI/CD variable, Vault through OIDC, and direct OIDC federation
From a stored variable to no stored secret at all.

Option 1: CI/CD variables

Set them at project or group level and mark them masked and protected. Protected variables are exposed only to pipelines on protected branches and tags, so main must be protected. Create them through the API (this one is scoped to the production environment):

# Needs a token with Maintainer role on the project; the value is read from stdin
tr -d '\n' < deploy-token.txt | curl --request POST \
  --header "PRIVATE-TOKEN: ${GITLAB_TOKEN}" \
  "https://gitlab.example.com/api/v4/projects/org%2Fpayments%2Fbilling-api/variables" \
  --form "key=DEPLOY_TOKEN" \
  --form "value=<-" \
  --form "masked=true" \
  --form "protected=true" \
  --form "environment_scope=production"

Option 2: Vault, authenticated with OIDC

The pipeline fetches secrets at runtime and nothing is stored in GitLab. On Premium, the secrets: keyword does it natively:

deploy:
  variables:
    VAULT_SERVER_URL: https://vault.example.com
    VAULT_AUTH_ROLE: billing-deploy
  id_tokens:
    VAULT_ID_TOKEN:
      aud: https://vault.example.com      # must match bound_audiences of the Vault role
  secrets:
    DB_PASSWORD:
      vault: payments/db/password@secret  # path payments/db, field password, mount "secret"
      token: $VAULT_ID_TOKEN
      file: false                         # default is a file; this exposes the value
  script: ./deploy.sh

The aud value must match bound_audiences on the Vault role. Also restrict the role with bound_claims such as project_id and ref. Without them, any job on the GitLab instance can log in with that role.

On the Free tier, use the same id_tokens and log in with the Vault CLI inside the job (the job image must contain it):

export VAULT_ADDR=https://vault.example.com
export VAULT_TOKEN="$(vault write -field=token auth/jwt/login role=billing-deploy jwt="$VAULT_ID_TOKEN")"
DB_PASSWORD="$(vault kv get -field=password secret/payments/db)"

Option 3: direct OIDC federation, with no stored secret

Option 2 uses GitLab's JSON Web Token (JWT) to log in to Vault. Option 3 skips the secrets store: the target system (a cloud provider, a Kubernetes cluster, an internal API) trusts GitLab directly as an identity provider and grants short-lived access for the lifetime of a job.

On AWS, register GitLab once as an IAM OIDC identity provider (URL https://gitlab.example.com, audience sts.amazonaws.com) and create a deploy role that only main of 1 project can assume:

{
  "Effect": "Allow",
  "Principal": { "Federated": "arn:aws:iam::123456789012:oidc-provider/gitlab.example.com" },
  "Action": "sts:AssumeRoleWithWebIdentity",
  "Condition": {
    "StringEquals": {
      "gitlab.example.com:aud": "sts.amazonaws.com",
      "gitlab.example.com:sub": "project_path:org/payments/billing-api:ref_type:branch:ref:main"
    }
  }
}

The job requests an ID token, and the AWS CLI exchanges it for temporary credentials on its own:

deploy:
  image: registry.example.com/tools/aws-cli:2.0   # AWS CLI v2, a shell and deploy.sh's tools
  id_tokens:
    AWS_ID_TOKEN:
      aud: sts.amazonaws.com
  variables:
    AWS_ROLE_ARN: arn:aws:iam::123456789012:role/billing-api-deploy
    AWS_ROLE_SESSION_NAME: gitlab-$CI_JOB_ID
  script:
    - echo "$AWS_ID_TOKEN" > /tmp/web-identity-token
    - export AWS_WEB_IDENTITY_TOKEN_FILE=/tmp/web-identity-token
    - aws sts get-caller-identity             # temporary credentials, valid for this job only
    - ./deploy.sh production
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $CI_PIPELINE_SOURCE == "push"

A job from any other project or branch gets a token with a different sub, and AWS refuses it. On GitLab Self-Managed, AWS conditions can only use sub and aud, and sub contains the project path: renaming the group or the project breaks the policy. The official amazon/aws-cli image has aws as its entrypoint, so it needs entrypoint: [""] when a job uses it directly.

Run GitLab runners as code

Jenkins agents are on-premises machines, VMs or containers, each with labels. GitLab runners cover the same ground, with tags.

Choose the executor per job type

ExecutorUse it for
Docker or KubernetesMost jobs. Each job runs in a clean container from a pinned image, which removes "works on agent A only" problems
Autoscaling (docker-autoscaler, instance)Spiky load, when you want to pay only for the capacity you use
ShellOnly where a container is impossible: access to company infrastructure, special hardware, or licensed tools bound to a host

Any code that reaches a shell runner can do whatever the runner can do. Keep unverified code off this runner type.

Register and configure runners from Git

Treat runners like any other infrastructure: the configuration lives in Git and a tool applies it. A simple setup uses Ansible. Each runner host gets its config.toml from a template in the repository, so nobody edits runner settings by hand.

Split the work into 5 small roles:

  • runner_install installs the gitlab-runner package and service
  • runner_register creates the runner through the GitLab API (POST /user/runners) with its scope, tags and protection, and stores the returned glrt- authentication token for the template. Registration tokens are deprecated and scheduled for removal in GitLab 20.0, so skip the guides that still use them
  • runner_config renders config.toml and restarts the service through a handler, only when the file changes
  • runner_health checks the service, runs gitlab-runner verify and probes the metrics endpoint
  • runner_restart restarts the service on demand

A trimmed config.toml.j2 with the settings that matter most:

concurrent = {{ runner_concurrent }}
listen_address = ":9252"              # metrics endpoint (Prometheus format)

[[runners]]
  name         = "{{ inventory_hostname }}"
  url          = "https://gitlab.example.com"
  token        = "{{ runner_token }}"
  executor     = "docker"
  output_limit = 16384                # KB; the default 4096 truncates large logs
  [runners.docker]
    image       = "registry.example.com/build/toolchain:1.4"
    pull_policy = ["always"]

The metrics endpoint is for Prometheus only: bind it to a private address or firewall it. The main playbook chains the roles:

# site.yml
- name: Configure GitLab runners
  hosts: runners
  become: true
  roles:
    - runner_install
    - runner_register
    - runner_config

Let the fleet repair itself

Run the playbooks from a GitLab CI pipeline in a dedicated runners project. A merge to the default branch applies the configuration. A scheduled pipeline runs health.yml, which uses runner_health to find broken runners, then restarts them, or registers them again when their token is no longer valid.

Run this pipeline on a separate, small, trusted runner (protected, tagged runner-admin), outside the fleet it manages. A broken fleet cannot repair itself.

default:
  image: registry.example.com/tools/ansible:1.0
  tags: [runner-admin]
  before_script:
    - chmod 600 "$ANSIBLE_SSH_KEY"

apply:
  script:
    - ansible-playbook -i inventory.yml site.yml --private-key "$ANSIBLE_SSH_KEY"
  resource_group: runners
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $CI_PIPELINE_SOURCE == "push"

health:
  script:
    - ansible-playbook -i inventory.yml health.yml --private-key "$ANSIBLE_SSH_KEY"
  resource_group: runners
  rules:
    - if: $CI_PIPELINE_SOURCE == "schedule"

Keep the secrets out of Git and store them in GitLab:

  • RUNNER_ADMIN_TOKEN: an access token with the create_runner scope, from an administrator or an Owner of the target group, in a masked, protected CI/CD variable that runner_register reads from the environment
  • ANSIBLE_SSH_KEY: the Ansible SSH private key, in a protected file-type variable

Replace Jenkins plugins with GitLab features

Most Jenkins plugins connect Jenkins to systems it does not own: the SCM, the issue tracker, report viewers. In GitLab many of those connections are built in, so a long plugin list usually shrinks to a handful of features.

Jenkins pluginGitLab replacement
Gerrit Triggerrules: and merge request pipelines, with "Pipelines must succeed" in place of the Verified vote
Jira pluginsThe GitLab Jira integration, plus a small API call where pipelines comment on or transition issues
Throttle and lock pluginsresource_group:, and runner limits with dedicated tags
Report plugins (JUnit, coverage, static analysis, HTML)artifacts:reports and expose_as

Start from the plugin inventory and decide plugin by plugin. There are 3 outcomes: it maps to a GitLab feature, a small script in a versioned container image does the job, or it is no longer needed and you drop it. A few plugins have no equivalent, for example Active Choices for dynamic parameters.

Documentation follows the same path. In the old setup it lives in yet another service, such as Confluence. In GitLab, keep the docs in the repository and publish them with a pipeline to the project wiki (itself a Git repository you can push to) or to GitLab Pages. Teams that want 1 tool less can also plan and track work in GitLab in place of Jira.

Jenkinsfile to GitLab CI cheat sheet

The tables cover the rest of what a typical Jenkinsfile contains. The full variable list is in the predefined CI/CD variables reference.

Stages and parallelism

JenkinsGitLabNotes
stage('Build') { steps { ... } }stages: [build, test, deploy] and a job with stage: buildStages are declared once, globally. Jobs are assigned to them
Sequential stages (default)Sequential stages (default)Same behaviour
parallel { stage('B') {...} stage('C') {...} }Jobs B and C in the same stageJobs in 1 stage run in parallel, as far as runner capacity allows
Stage order as the only dependencyneeds: [job]A job starts as soon as the jobs it needs finish, regardless of stage
matrix { axes { axis { name 'OS'; values 'a', 'b' } } }parallel: matrix: - OS: [a, b]Matrix variables work in tags: and image:. Maximum 200 jobs

Agents and runners

JenkinsGitLabNotes
agent anyNo tags:Only runners with "Run untagged jobs" enabled pick it up
agent { label 'linux' }tags: [linux]OR expressions need a shared tag
agent { docker { image 'node:18' } }image: node:18Runs on a Docker or Kubernetes executor
agent none and an agent per stageimage: and tags: per jobThe usual GitLab style. Put shared values in default:

Triggers

JenkinsGitLabNotes
Gerrit Trigger pluginPush and merge request eventsBuilt in. Filters become rules:
triggers { cron('H/15 * * * *') }Pipeline scheduleConfigured in the UI or the API. Replace H with a fixed minute
triggers { pollSCM(...) }Not neededPipelines start on push
"Build Now""New pipeline" ("Run pipeline" before GitLab 17.7), or a job with when: manualManual jobs show a play button in the pipeline
build job: 'downstream'trigger: project: group/downstreamMulti-project pipeline. Add strategy: mirror to wait for its result (strategy: depend before GitLab 18.2)
Parameterized triggertrigger: and variables:Variables are passed to the downstream pipeline
Remote trigger /build?token=...Pipeline trigger tokenPOST /api/v4/projects/:id/trigger/pipeline. Update every caller
Upstream trigger (build after another job)A trigger: job in the upstream projectDefined on the upstream side

Conditions

JenkinsGitLab
when { branch 'main' }rules: - if: $CI_COMMIT_BRANCH == "main"
when { not { branch 'main' } }rules: - if: $CI_COMMIT_BRANCH != "main"
when { tag 'v*' }rules: - if: $CI_COMMIT_TAG =~ /^v/
when { changeset '**/*.java' }rules: - changes: ["**/*.java"]
when { expression { return params.DEPLOY } }rules: - if: $DEPLOY == "true"
when { environment name: 'DEPLOY_TO', value: 'prod' }rules: - if: $DEPLOY_TO == "prod"
when { allOf { branch 'main'; expression { params.DEPLOY } } }rules: - if: $CI_COMMIT_BRANCH == "main" && $DEPLOY == "true"

A branch condition and a tag condition cannot be combined with AND. Tag pipelines have no CI_COMMIT_BRANCH, so the rule never matches.

Artifacts

JenkinsGitLabNotes
archiveArtifacts artifacts: '**/*.jar'artifacts: paths: ["**/*.jar"]Add expire_in
fingerprint: trueNo equivalentArtifacts are tracked per job and pipeline
stash name: 'build', includes: '**/*.o'artifacts: on the producing jobShort expire_in, for example 1 day
unstash 'build'needs: [build] or dependencies: [build]needs also starts the job early. dependencies only selects artifacts
copyArtifacts projectName: 'other'needs: [{project: group/other, job: build, ref: main, artifacts: true}]Premium. On Free, use the job artifacts API
Keep build foreverexpire_in: never, or "Keep" on the job pageUse for releases only
Discard old buildsexpire_in: 1 weekPlus the project pipeline retention settings

An extended example: parallel checks, a matrix, stash, approval and a downstream trigger

The Jenkinsfile:

pipeline {
  agent none
  triggers { cron('H 2 * * *') }

  stages {
    stage('Build') {
      agent { docker { image 'maven:3.9-eclipse-temurin-21' } }
      steps {
        sh 'mvn -B package -DskipTests'
        stash name: 'jar', includes: 'target/*.jar'
      }
    }
    stage('Checks') {
      parallel {
        stage('Unit tests') {
          agent { docker { image 'maven:3.9-eclipse-temurin-21' } }
          steps { sh 'mvn -B test' }
          post { always { junit 'target/surefire-reports/*.xml' } }
        }
        stage('Lint') {
          agent { docker { image 'maven:3.9-eclipse-temurin-21' } }
          when { changeset '**/*.java' }
          steps { sh 'mvn -B checkstyle:check' }
        }
      }
    }
    stage('Integration') {
      matrix {
        axes {
          axis { name 'PLATFORM'; values 'linux-amd64', 'linux-arm64' }
          axis { name 'JDK'; values '17', '21' }
        }
        agent { label "${PLATFORM}" }
        stages {
          stage('IT') {
            steps {
              unstash 'jar'
              sh "./it.sh --jdk ${JDK}"
            }
          }
        }
      }
    }
    stage('Release') {
      agent { label 'linux-amd64' }
      when { tag 'v*' }
      steps {
        input message: 'Deploy to production?'
        unstash 'jar'
        sh './deploy.sh production'
        archiveArtifacts artifacts: 'target/*.jar', fingerprint: true
      }
    }
    stage('E2E') {
      when { branch 'main' }
      steps {
        build job: 'org/e2e-tests', wait: false,
              parameters: [string(name: 'APP_VERSION', value: env.GIT_COMMIT)]
      }
    }
  }
}

The equivalent .gitlab-ci.yml (add the workflow: block from the first example):

default:
  image: maven:3.9-eclipse-temurin-21
  tags: [linux-docker]

stages: [build, checks, integration, release, e2e]

build:
  stage: build
  script: mvn -B package -DskipTests
  artifacts:                                  # stash 'jar'
    paths: [target/*.jar]
    expire_in: 1 week                         # must outlast the manual release

unit-tests:
  stage: checks                               # same stage as lint -> parallel
  script: mvn -B test
  artifacts:
    when: always
    expire_in: 2 weeks
    reports:
      junit: target/surefire-reports/*.xml

lint:
  stage: checks
  script: mvn -B checkstyle:check
  rules:
    - changes: ["**/*.java"]                  # when { changeset }

integration:
  stage: integration
  tags: ["$PLATFORM"]                         # agent { label "${PLATFORM}" }
  parallel:
    matrix:                                   # 2 x 2 = 4 jobs
      - PLATFORM: [linux-amd64, linux-arm64]
        JDK: ["17", "21"]
  needs: [build]                              # unstash 'jar'; starts as soon as build is done
  script: ./it.sh --jdk "$JDK"

release:
  stage: release
  tags: [linux-amd64]
  rules:
    - if: $CI_COMMIT_TAG =~ /^v/
      when: manual                            # input message: 'Deploy to production?'
  environment: production
  resource_group: production
  dependencies: [build]                       # unstash 'jar'; still waits for earlier stages
  script: ./deploy.sh production
  artifacts:                                  # archiveArtifacts, kept for the release
    paths: [target/*.jar]
    expire_in: never

e2e-tests:
  stage: e2e
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $CI_PIPELINE_SOURCE == "push"
  variables:
    APP_VERSION: $CI_COMMIT_SHA               # passed to the downstream pipeline
  trigger:                                    # build job: ..., wait: false
    project: org/e2e-tests
    branch: main

3 things to note:

  • Integration jobs no longer wait for the checks stage, because needs: lets them start right after build. Drop needs: if they must wait
  • An input step inside an agent holds that executor while it waits. A GitLab manual job uses no runner until someone presses play
  • The manual release job downloads the build artifact, so expire_in on build has to outlast the wait for approval (1 week here). An expired artifact fails the job

Jenkins to GitLab migration checklist

  1. GitLab tier checked against the features the plan uses
  2. Inventory exported: jobs, triggers, labels, last run date, owner, plugins, shared libraries, credential IDs, inbound callers
  3. Jobs with no run in 90 days or no owner deleted from scope
  4. Group structure designed, membership driven by the identity provider
  5. Repositories mirrored, mirrored branches writable only by the mirror
  6. 1 reference pipeline written by hand and approved
  7. Every tags: list matches a real runner, with no OR hidden in it
  8. Every secret recreated from its source, none copied from config.xml
  9. Pipeline schedules created for every cron trigger
  10. Scoreboard per repository shows Jenkins and GitLab agreeing
  11. Rollback triggers agreed and written down
  12. Cutover done per repository group: old SCM read-only, Jenkins jobs disabled and kept
  13. Inbound callers repointed: trigger API, badges, webhooks
  14. 2 weeks of pipeline health checked against the Jenkins baseline, then sign-off

Jenkins to GitLab migration FAQ

How long does a Jenkins to GitLab migration take?

With the plan in this guide: 4 to 8 weeks of preparation, 2 to 4 weeks of user acceptance, 1 day of cutover per repository group, and 2 weeks of post-cutover checks. That is roughly 2 to 4 months for a stack with Gerrit or SVN. Pruning dead jobs first is the fastest way to shorten it.

What is the GitLab equivalent of a Jenkinsfile?

The .gitlab-ci.yml file in the root of the repository. It is YAML where a Jenkinsfile is Groovy, and 1 file covers every event for the project: pushes, merge requests, tags, schedules and manual runs.

Can Jenkins credentials be exported to GitLab?

The IDs can, the values cannot. Encrypted values in config.xml and credentials.xml are tied to the old controller's key. Recreate each secret from its real source as a masked CI/CD variable, a Vault path, or an OIDC trust with no stored secret.

What replaces Jenkins shared libraries in GitLab?

CI/CD components and include: templates replace the pipeline structure in vars/*.groovy. Library parameters become component inputs, the @Library version becomes a component version, and Groovy logic moves into scripts in a versioned container image.

What is the GitLab equivalent of a Jenkins agent label?

Runner tags. A job lists tags, and a runner picks the job up only when it has all of them. Jenkins label expressions with OR have no direct translation: add 1 shared tag to the runners of both pools.

Can Jenkins and GitLab CI run side by side during the migration?

Yes, and they should for 2 to 4 weeks. Mirror the repositories into GitLab, let both systems build the same commits, and compare results per repository. Cut a repository over when the 2 agree consistently.

Is GitLab CI better than Jenkins?

For a team that already moves its code to GitLab, yes: code, review, pipelines, secrets and access control live in 1 system, and most plugins become built-in features. Jenkins keeps an edge where a pipeline depends on a plugin with no GitLab counterpart, such as Active Choices dynamic parameters, or on Gerrit topics for atomic changes across repositories.

Where to go from here

Start with the inventory and the prune: both need only read access to Jenkins, and they decide the size of everything after. Then write the reference pipeline, and hand the jenkins2gitlab skill file and the cheat sheet above to whoever (or whatever) translates the rest.

Related guides: CI/CD Pipeline, Azure DevOps vs GitLab for Startups and When to Use GitOps.

If you want senior engineers to review your migration plan with you, book a free DevOps assessment.