Of course! "Ubuntu Gerrit Python" can mean a few different things. Let's break it down into the most common scenarios, from the simplest to the most advanced.

Here’s a comprehensive guide covering:
- Scenario 1: Running a Python script on Ubuntu that interacts with a Gerrit server. (Most Common)
- Scenario 2: Setting up and running a Gerrit server on Ubuntu.
- Scenario 3: Using Gerrit's Python-based plugins.
- Scenario 4: The Gerrit codebase itself, which is written in Python.
Scenario 1: Running a Python Script to Interact with Gerrit (Most Common)
This is the most frequent use case. You have a Gerrit instance (e.g., review.myproject.org) and you want to write a Python script to automate tasks like creating changes, adding reviewers, or querying changes.
Key Tool: PyGerrit
The standard and most powerful library for this is PyGerrit. It provides a Pythonic wrapper around the Gerrit REST API.
Installation

First, ensure you have Python and pip installed on your Ubuntu system.
# Update package lists sudo apt update # Install Python 3 and pip if you don't have them sudo apt install python3 python3-pip # Install PyGerrit using pip pip3 install PyGerrit2
Authentication
Gerrit requires authentication. The two most common methods are HTTP Login (username/password) and SSH Key-based authentication.
- HTTP Login: Simpler to set up but less secure for scripts.
- SSH Key (Recommended): More secure and common for automation. You need to have your SSH public key added to your Gerrit user account.
Example Python Scripts

Let's look at some practical examples. Remember to replace placeholders like YOUR_GERRIT_URL, YOUR_USERNAME, etc.
Example A: Querying Changes (using SSH)
This script connects via SSH and lists all open changes for the my-awesome-project project.
# gerrit_query.py
from pygerrit import GerritRestAPI, GerritSSHClient
from pygerrit.utils import decode_json
# --- Configuration ---
GERRIT_URL = "review.myproject.org" # No http/https, just hostname
USERNAME = "your-gerrit-username"
PROJECT = "my-awesome-project"
# --- Method 1: Using SSH (Recommended for read/write) ---
def query_changes_ssh():
print(f"Connecting to {GERRIT_URL} via SSH as {USERNAME}...")
try:
# The GerritSSHClient handles the connection and command execution
with GerritSSHClient(host=GERRIT_URL, username=USERNAME) as gerrit:
# The query command is sent as a string
# 'o' is for option, 'CURRENT_REVISION' is useful
command = f"gerrit query project:{PROJECT} status:open limit:10 o=CURRENT_REVISION"
# The result is a string, we need to parse it
result_str = gerrit(command)
print("SSH Command Output:")
print(result_str)
print("\n--- Parsed Results ---")
# The output is a series of JSON objects separated by newlines
# and a final line with a 'type' field. We can split and parse.
lines = result_str.strip().split('\n')
for line in lines:
if line.startswith('{') and not line.endswith(','):
try:
change_info = decode_json(line)
if change_info.get('type') == 'stats':
continue # Skip the stats line at the end
print(f" - Change #{change_info['number']}: {change_info['subject']}")
print(f" Project: {change_info['project']}, Branch: {change_info['branch']}")
except Exception as e:
print(f"Could not parse line: {line}. Error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
query_changes_ssh()
Example B: Creating a New Change (using REST API with HTTP Login)
This script creates a new change by uploading a patch set. Note: This requires the requests library, which PyGerrit depends on.
# gerrit_create_change.py
import base64
import requests
from pygerrit import GerritRestAPI
# --- Configuration ---
GERRIT_URL = "https://review.myproject.org" # Full URL with https
USERNAME = "your-gerrit-username"
PASSWORD = "your-gerrit-password" # Or use an OAuth token
PROJECT = "my-awesome-project"
BRANCH = "main"
FILE_PATH = "src/main.py"
FILE_CONTENT = "# This is a new file\nprint('Hello from Gerrit!')\n"
COMMIT_MSG = "Create new file via PyGerrit"
# --- Method 2: Using REST API (Good for HTTP-based auth) ---
def create_change_rest():
print(f"Connecting to {GERRIT_URL} via REST API as {USERNAME}...")
# GerritRestAPI can handle basic authentication
gerrit = GerritRestAPI(url=GERRIT_URL, auth=(USERNAME, PASSWORD))
# Step 1: Create a new change (returns the change ID)
change_input = {
"project": PROJECT,
"branch": BRANCH,
"subject": COMMIT_MSG,
"files": {
FILE_PATH: {
"type": "ADDED", # Use "MODIFIED" or "REMOVED" as needed
"content": base64.b64encode(FILE_CONTENT.encode('utf-8')).decode('utf-8')
}
}
}
try:
# The endpoint for creating a change is /a/changes/
# The 'a' prefix means authentication is required
response = gerrit.post("/a/changes/", json=change_input, headers={"Content-Type": "application/json"})
print(f"Successfully created change. Response: {response}")
# The response contains the change ID, e.g., "my-change-id~Iabc123..."
change_id = response['id']
print(f"New Change ID: {change_id}")
# Step 2: Publish the change (submit it for review)
# The action is 'submit'
submit_input = {"message": "Submitting change for review."}
gerrit.post(f"/a/changes/{change_id}/revisions/current/review", json=submit_input, headers={"Content-Type": "application/json"})
print(f"Change {change_id} has been submitted for review.")
except requests.exceptions.HTTPError as err:
print(f"HTTP Error: {err}")
if err.response.status_code == 401:
print("Authentication failed. Check your username and password.")
elif err.response.status_code == 404:
print("Project or branch not found.")
else:
print(f"An HTTP error occurred: {err.response.text}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
create_change_rest()
Scenario 2: Setting up a Gerrit Server on Ubuntu
If you want to host your own Gerrit instance, you can do so on an Ubuntu server.
System Requirements
- A fresh Ubuntu Server (20.04 LTS or 22.04 LTS recommended).
- At least 4GB of RAM (8GB+ recommended).
- Sufficient disk space (50GB+ for a medium-sized team).
- A Java Development Kit (JDK) 11 or 17.
Installation Steps
The easiest way to install Gerrit is by using its deb package.
# 1. Update your system sudo apt update && sudo apt upgrade -y # 2. Install Java (OpenJDK 17 is a good choice) sudo apt install -y openjdk-17-jdk # 3. Add the Gerrit repository and install the package # You can find the latest version on the Gerrit download page wget https://gerrit-releases.storage.googleapis.com/gerrit-3.8.4.war sudo java -jar gerrit-3.8.4.war init -d /var/gerrit_review # This will start an interactive setup script. Here are the recommended answers: # -- Welcome to Gerrit Code Review -- [OK] # No database selected [H2] # [localhost:3306] [mysql] # [root] [password] # [reviewdb] [gerrit] # [gerrit] [gerrit] # [db] [db] # [yes] [yes] # [auto] [auto] # [all] [all] # [no] [no] # [yes] [yes] # [HTTPD] [listen *:8080] # [yes] [yes] # [email] [email] # [web] [web] # [all] [all] # [yes] [
