GitLab Rails Console Cheat Sheet

This is the GitLab Support Team's collection of information regarding the GitLab Rails console, for use while troubleshooting. It is listed here for transparency, and it may be useful for users with experience with these tools. If you are currently having an issue with GitLab, it is highly recommended that you check your support options first, before attempting to use this information.

CAUTION: CAUTION: Please note that some of these scripts could be damaging if not run correctly, or under the right conditions. We highly recommend running them under the guidance of a Support Engineer, or running them in a test environment with a backup of the instance ready to be restored, just in case.

CAUTION: CAUTION: Please also note that as GitLab changes, changes to the code are inevitable, and so some scripts may not work as they once used to. These are not kept up-to-date as these scripts/commands were added as they were found/needed. As mentioned above, we recommend running these scripts under the supervision of a Support Engineer, who can also verify that they will continue to work as they should and, if needed, update the script for the latest version of GitLab.

Use the Rails Runner

If the script you want to run is short, you can use the Rails Runner to avoid entering the rails console in the first place. Here's an example of its use:

gitlab-rails runner "RAILS_COMMAND"

# Example with a 2-line script
gitlab-rails runner "user = User.first; puts user.username"

Enable debug logging on rails console

Rails.logger.level = 0

Enable debug logging for ActiveRecord (db issues)

ActiveRecord::Base.logger =

Temporarily Disable Timeout

ActiveRecord::Base.connection.execute('SET statement_timeout TO 0')

Find specific methods for an object { |m| m.to_s.include? "sing" }

Find method source

Works for non-instrumented methods:


# Example for when we would call project.private?

Query an object

o = Object.where('attribute like ?', 'ex')

View all keys in cache


Rails console history

puts Readline::HISTORY.to_a

Profile a page

# Before 11.6.0
logger =
admin_token = User.find_by_username('ADMIN_USERNAME').personal_access_tokens.first.token

# From 11.6.0
admin = User.find_by_username('ADMIN_USERNAME')
url = "/url/goes/here"
Gitlab::Profiler.with_user(admin) { app.get(url) }

Using the GitLab profiler inside console (used as of 10.5)

logger =
admin = User.find_by_username('ADMIN_USERNAME')
Gitlab::Profiler.profile('URL', logger: logger, user: admin)

Time an operation

# A single operation
Benchmark.measure { <operation> }

# A breakdown of multiple operations do |x| { <operation_1> } { <operation_2> }

Command Line

Check the GitLab version fast

grep -m 1 gitlab /opt/gitlab/version-manifest.txt

Debugging SSH

GIT_SSH_COMMAND="ssh -vvv" git clone <repository>

Debugging over HTTPS

GIT_CURL_VERBOSE=1 GIT_TRACE=1 git clone <repository>


Find projects

# A single project
project = Project.find_by_full_path('PROJECT_PATH')

# All projects in a particular namespace.  Can be a username, a group
# ('gitlab-org'), or even include subgroups ('gitlab-org/distribution')
namespace = Namespace.find_by_full_path('NAMESPACE_PATH')
projects = namespace.all_projects

Clear a project's cache


Expire the .exists? cache


Make all projects private

Project.update_all(visibility_level: 0)

Find & remove projects that are pending deletion

# This section will list all the projects which are pending deletion
projects = Project.where(pending_delete: true)
projects.each do |p|
  puts "Project name: #{}"
  puts "Project name: #{}"
  puts "Repository path: #{p.repository.storage_path}"

# Assign a user (the root user will do)
user = User.find_by_username('root')

# For each project listed repeat these two commands

# Find the project, update the xxx-changeme values from above
project = Project.find_by_full_path('group-changeme/project-changeme')

# Delete the project, user, {}).execute

Next, run sudo gitlab-rake gitlab:cleanup:repos on the command line to finish.

Destroy a project

project = Project.find_by_full_path('')
user = User.find_by_username('')
ProjectDestroyWorker.perform_async(,, {})
# or,, {})
# or, user).execute

Remove fork relationship manually

p = Project.find_by_full_path('')
u = User.find_by_username(''), u).execute

Make a project read-only (can only be done in the console)

# Make a project read-only
project.repository_read_only = true;

# OR
project.update!(repository_read_only: true)

Bulk update service integration password for all projects

For example, change the Jira user's password for all projects that have the Jira integration active:

p = Project.find_by_sql("SELECT FROM projects p LEFT JOIN services s ON = s.project_id WHERE s.type = 'JiraService' AND = true")

p.each do |project|
  project.jira_service.update_attribute(:password, '<your-new-password>')

Identify un-indexed projects

Project.find_each do |project|
  puts "id #{}: #{}/#{}" if project.index_status.nil?



A Projects Wiki can be recreated by

Note: This is a destructive operation, the Wiki will be empty

p = Project.find_by_full_path('<username-or-group>/<project-name>')  ### enter your projects path

GitlabShellWorker.perform_in(0, :remove_repository, p.repository_storage,  ### deletes the wiki project from the filesystem

p.create_wiki  ### creates the wiki project on the filesystem

Imports / Exports

# Find the project and get the error
p = Project.find_by_full_path('<username-or-group>/<project-name>')


# To finish the import on GitLab running version before 11.6

# To finish the import on GitLab running version 11.6 or after
p.import_state.mark_as_failed("Failed manually through console.")

Rename imported repository

In a specific situation, an imported repository needed to be renamed. The Support Team was informed of a backup restore that failed on a single repository, which created the project with an empty repository. The project was successfully restored to a dev instance, then exported, and imported into a new project under a different name.

The Support Team was able to transfer the incorrectly named imported project into the correctly named empty project using the steps below.

Move the new repository to the empty repository:

mv /var/opt/gitlab/git-data/repositories/<group>/<new-project> /var/opt/gitlab/git-data/repositories/<group>/<empty-project>

Make sure the permissions are correct:

chown -R git:git <path-to-directory>.git

Clear the cache:

sudo gitlab-rake cache:clear


Search sequence of pushes to a repository

If it seems that a commit has gone "missing", search the sequence of pushes to a repository. This StackOverflow article describes how you can end up in this state without a force push.

If you look at the output from the sample code below for the target branch, you will see a discontinuity in the from/to commits as you step through the output. Each new push should be "from" the "to" SHA of the previous push. When this discontinuity happens, you will see two pushes with the same "from" SHA:

p = Project.find_with_namespace('u/p') do |e|
  printf "%-20.20s %8s...%8s (%s)\n",[:ref],[:before],[:after],

GitLab 9.5 and above:

p = Project.find_by_full_path('u/p') do |e|
  printf "%-20.20s %8s...%8s (%s)\n", e.push_event_payload[:ref], e.push_event_payload[:commit_from], e.push_event_payload[:commit_to],


Find mirrors with "bad decrypt" errors

total = 0
bad = []
ProjectImportData.find_each do |data|
    total += 1
  rescue => e
    bad << data

puts "Bad count: #{bad.count} / #{total}"
bad.each do |repo|
  puts Project.find(repo.project_id).full_path
end; bad.count

Transfer mirror users and tokens to a single service account

Use case: If you have multiple users using their own GitHub credentials to set up repository mirroring, mirroring breaks when people leave the company. Use this script to migrate disparate mirroring users and tokens into a single service account:

svc_user = User.find_by(username: 'ourServiceUser')
token = 'githubAccessToken'

Project.where(mirror: true).each do |project|
  import_url = project.import_url

  # The url we want is https://token@project/path.git
  repo_url = if import_url.include?('@')
               # Case 1: The url is something like https://23423432@project/path.git
             elsif import_url.include?('//')
               # Case 2: The url is something like https://project/path.git

  next unless repo_url

  final_url = "https://#{token}@#{repo_url}"

  project.mirror_user = svc_user
  project.import_url = final_url
  project.username_only_import_url = final_url


Finding users

# By username
user = User.find_by(username: '')

# By primary email
user = User.find_by(email: '')

# By any email (primary or secondary)
user = User.find_by_any_email('')

# Admins
admin = User.admins.first





Skip reconfirmation

user = User.find_by_username ''

Get an admin token

# Get the first admin's first access token (no longer works on 11.9+. see:

# Get the first admin's private token (no longer works on 10.2+)

Create personal access token

personal_access_token = User.find(123).personal_access_tokens.create(
  name: 'apitoken',
  impersonation: false,
  scopes: [:api]

puts personal_access_token.token

You might also want to manually set the token string:

  name: 'apitoken',
  token_digest: Gitlab::CryptoHelper.sha256('some-token-string-here'),
  impersonation: false,
  scopes: [:api]

Disable 2FA on a user

user = User.find_by_username('username')

Active users & Historical users

# Active users on the instance, now

# The historical max on the instance as of the past year
# Using curl and jq (up to a max 100, see pagination docs
curl --silent --header "Private-Token: ********************" "" | jq --compact-output '.[] | [.id,.name,.username]'

Block or Delete Users that have no projects or groups

users = User.where('id NOT IN (select distinct(user_id) from project_authorizations)')

# How many users will be removed?

# If that count looks sane:

# You can either block the users:
users.each { |user| user.block! }

# Or you can delete them:
  # need 'current user' (your user) for auditing purposes
current_user = User.find_by(username: '<your username>')

users.each do |user|

Block Users that have no recent activity

days_inactive = 60
inactive_users ="last_activity_on <= ?", days_inactive.days.ago)

inactive_users.each do |user|
    puts "user '#{user.username}': #{user.last_activity_on}"

Find Max permissions for project/group

user = User.find_by_username 'username'
project = Project.find_by_full_path 'group/project'
user = User.find_by_username 'username'
group = Group.find_by_full_path 'group'


Count unique users in a group and sub-groups

group = Group.find_by_path_or_name("groupname")
members = []
for member in group.members_with_descendants

group = Group.find_by_path_or_name("groupname")

# Count users from subgroup and up (inherited)

# Count users from parent group and down (specific grants)

Delete a group

GroupDestroyWorker.perform_async(group_id, user_id)

Modify group project creation

# Project creation levels: 0 - No one, 1 - Maintainers, 2 - Developers + Maintainers
group = Group.find_by_path_or_name('group-name')


LDAP commands in the rails console

TIP: TIP: Use the rails runner to avoid entering the rails console in the first place. This is great when only a single command (such as a UserSync or GroupSync) is needed.

# Get debug output
Rails.logger.level = Logger::DEBUG

# Run a UserSync (normally performed once a day)

# Run a GroupSync for all groups (9.3-)

# Run a GroupSync for all groups (9.3+)

# Run a GroupSync for a single group (10.6-)
group = Group.find_by(name: 'my_gitlab_group')

# Run a GroupSync for a single group (10.6+)
group = Group.find_by(name: 'my_gitlab_group')

# Query an LDAP group directly (10.6-)
adapter ='ldapmain') # If `main` is the LDAP provider
ldap_group = EE::Gitlab::LDAP::Group.find_by_cn('group_cn_here', adapter)

# Query an LDAP group directly (10.6+)
adapter ='ldapmain') # If `main` is the LDAP provider
ldap_group = EE::Gitlab::Auth::LDAP::Group.find_by_cn('group_cn_here', adapter)

# Lookup a particular user (10.6+)
# This could expose potential errors connecting to and/or querying LDAP that may seem to
# fail silently in the GitLab UI
adapter ='ldapmain') # If `main` is the LDAP provider
user = Gitlab::Auth::LDAP::Person.find_by_uid('<username>',adapter)

# Query the LDAP server directly (10.6+)
## For an example, see
adapter ='ldapmain')
options = {
    # the :base is required
    # use adapter.config.base for the base or .group_base for the group_base
    base: adapter.config.group_base,

    # :filter is optional
    # 'cn' looks for all "cn"s under :base
    # '*' is the search string - here, it's a wildcard
    filter: Net::LDAP::Filter.eq('cn', '*'),

    # :attributes is optional
    # the attributes we want to get returned
    attributes: %w(dn cn memberuid member submember uniquemember memberof)

Update user accounts when the dn and email change

The following will require that any accounts with the new email address are removed. Emails have to be unique in GitLab. This is expected to work but unverified as of yet:

# Here's an example with a couple users.
# Each entry will have to include the old username and the new email
emails = {

emails.each do |username, email|
  user = User.find_by_username(username) = email

# Run the UserSync to update the above users' data


Remove redirecting routes


path = 'foo'
conflicting_permanent_redirects = RedirectRoute.matching_path_and_descendants(path)

# Check that conflicting_permanent_redirects is as expected

Merge Requests

Find Merge Request

m = project.merge_requests.find_by(iid: <IID>)
m = MergeRequest.find_by_title('NEEDS UNIQUE TITLE!!!')

Close a merge request properly (if merged but still marked as open)

p = Project.find_by_full_path('')
m = project.merge_requests.find_by(iid: )
u = User.find_by_username(''), u).execute(m)

Delete a merge request

u = User.find_by_username('<username>')
p = Project.find_by_full_path('<group>/<project>')
m = p.merge_requests.find_by(iid: <IID>), u).execute(m)

Rebase manually

p = Project.find_by_full_path('')
m = project.merge_requests.find_by(iid: )
u = User.find_by_username(''), u).execute(m)


Cancel stuck pending pipelines

For more information, see the confidential issue

Ci::Pipeline.where(project_id: 'pending').count
Ci::Pipeline.where(project_id: 'pending').each {|p| p.cancel if p.stuck?}
Ci::Pipeline.where(project_id: 'pending').count

Manually modify runner minutes

Namespace.find_by_full_path("user/proj").namespace_statistics.update(shared_runners_seconds: 27360)

Remove artifacts more than a week old

The Latest version of these steps can be found in the job artifacts documentation

# For a single project:
project = Project.find_by_full_path('')
builds_with_artifacts =  project.builds.with_artifacts_archive

# Instance-wide:
builds_with_artifacts = Ci::Build.with_artifacts_archive

# Prior to 10.6 the above lines would be:
# builds_with_artifacts =  project.builds.with_artifacts
# builds_with_artifacts = Ci::Build.with_artifacts

# Note that this will also erase artifacts that developers marked to "Keep"
builds_to_clear = builds_with_artifacts.where("finished_at < ?", 1.week.ago)
builds_to_clear.each do |build|
  build.artifacts_expire_at =

Find reason failure (for when build trace is empty) (Introduced in 10.3.0)


build = Ci::Build.find(78420)


build.dependencies.each do |d| { puts "status: #{d.status}, finished at: #{d.finished_at},
  completed: #{d.complete?}, artifacts_expired: #{d.artifacts_expired?}, erased: #{d.erased?}" }

Disable strict artifact checking (Introduced in GitLab 10.3.0)

See job artifacts documentation.


Remove CI traces older than 6 months

current_user = User.find_by_email('')
Ci::Build.where("finished_at < ?", 6.months.ago.to_date).each {|b| puts; b.erase(erased_by: current_user) if b.erasable?};nil

Try CI service

p = Project.find_by_full_path('')
m = project.merge_requests.find_by(iid: )

Disable AutoDevOps on Existing Projects

Project.all.each do |p|


See license plan name (since v9.3.0-ee)


Check if a project feature is available on the instance

Features listed in


Check if a project feature is available in a project

Features listed in

p = Project.find_by_full_path('<group>/<project>')

Add a license through the console

key = "<key>"
license = key)
License.current # check to make sure it applied


From Zendesk ticket #91083 (internal)

Poll Unicorn requests by seconds

require 'rubygems'
require 'unicorn'

# Usage for this program
def usage
  puts "ruby unicorn_status.rb <path to unix socket> <poll interval in seconds>"
  puts "Polls the given Unix socket every interval in seconds. Will not allow you to drop below 3 second poll intervals."
  puts "Example: /opt/gitlab/embedded/bin/ruby poll_unicorn.rb /var/opt/gitlab/gitlab-rails/sockets/gitlab.socket 10"

# Look for required args. Throw usage and exit if they don't exist.
if ARGV.count < 2
  exit 1

# Get the socket and threshold values.
socket = ARGV[0]
threshold = (ARGV[1]).to_i

# Check threshold - is it less than 3? If so, set to 3 seconds. Safety first!
if threshold.to_i < 3
  threshold = 3

# Check - does that socket exist?
unless File.exist?(socket)
  puts "Socket file not found: #{socket}"
  exit 1

# Poll the given socket every THRESHOLD seconds as specified above.
puts "Running infinite loop. Use CTRL+C to exit."
puts "------------------------------------------"
loop do
  Raindrops::Linux.unix_listener_stats([socket]).each do |addr, stats|
    puts + " Active: " + + " Queued: " + stats.queued.to_s
  sleep threshold


Size of a queue'background_migration').size

Kill a worker's Sidekiq jobs

queue ='repository_import')
queue.each { |job| job.delete if <condition>}

<condition> probably includes references to job arguments, which depend on the type of job in question.

queue worker job args
repository_import RepositoryImportWorker project_id
update_merge_requests UpdateMergeRequestsWorker project_id, user_id, oldrev, newrev, ref

Example: Delete all UpdateMergeRequestsWorker jobs associated with a merge request on project_id 125, merging branch ref/heads/my_branch.

queue ='update_merge_requests')
queue.each { |job| job.delete if job.args[0]==125 and job.args[4]=='ref/heads/my_branch'}

Note: Running jobs will not be killed. Stop Sidekiq before doing this, to get all matching jobs.

Enable debug logging of Sidekiq

gitlab_rails['env'] = {

Then gitlab-ctl reconfigure; gitlab-ctl restart sidekiq. The Sidekiq logs will now include additional data for troubleshooting.

Sidekiq kill signals



Connect to Redis (omnibus)

/opt/gitlab/embedded/bin/redis-cli -s /var/opt/gitlab/redis/redis.socket

Connect to Redis (HA)

/opt/gitlab/embedded/bin/redis-cli -h <host ip> -a <password>


Get info about LFS objects and associated project

o=LfsObject.find_by(oid: "<oid>")

You can then delete these records from the database with:


You would also want to combine this with deleting the LFS file in the LFS storage area on disk. It remains to be seen exactly how or whether the deletion is useful, however.

Decryption Problems

Bad Decrypt Script (for encrypted variables)


This script will go through all the encrypted variables and count how many are not able to be decrypted. Might be helpful to run on multiple nodes to see which gitlab-secrets.json file is most up to date:

wget -O /tmp/bad-decrypt.rb
gitlab-rails runner /tmp/bad-decrypt.rb

If ProjectImportData Bad count: is detected and the decision is made to delete the encrypted credentials to allow manual reentry:

  # Find the ids of the corrupt ProjectImportData objects
  total = 0
  bad = []
  ProjectImportData.find_each do |data|
      total += 1
    rescue => e
      bad <<

  puts "Bad count: #{bad.count} / #{total}"

  # See the bad ProjectImportData ids

  # Remove the corrupted credentials
  import_data = ProjectImportData.where(id: bad)
  import_data.each do |data|
    data.update_columns({ encrypted_credentials: nil, encrypted_credentials_iv: nil, encrypted_credentials_salt: nil})

If User OTP Secret Bad count: is detected. For each user listed disable/enable two-factor authentication.

Decrypt Script for encrypted tokens

This script will search for all encrypted tokens that are causing decryption errors, and update or reset as needed:

wget -O /tmp/encrypted-tokens.rb
gitlab-rails runner /tmp/encrypted-tokens.rb



Find failed artifacts


Download artifact, <artifact_id>).execute

Get a count of the synced artifacts


Find ID of synced artifacts that are missing on primary


Repository verification failures

Get the number of verification failed repositories

Find the verification failed repositories


Find repositories that failed to sync'repository')

Resync repositories

Queue up all repositories for resync. Sidekiq will handle each sync

Geo::ProjectRegistry.update_all(resync_repository: true, resync_wiki: true)

Sync individual repository now

project = Project.find_by_full_path('<group/project>')