Many companies run their pipelines on Jenkins, often on their own servers next to internal test environments. A Jenkins pipeline for Playwright Python does the same job as a GitHub Actions workflow: get the code, prepare Python and browsers, run pytest, and keep results and evidence. In this lesson you will write a declarative Jenkinsfile that runs inside the official Playwright Docker image, passes credentials safely, takes build parameters, records JUnit results for trend charts, publishes HTML and Allure reports, archives failure artifacts, runs browsers in parallel stages and works on Windows agents too.
📖 What You’ll Learn: Jenkins pipeline basics, a declarative Jenkinsfile, a Docker agent with the Playwright Python image, a virtual environment on plain agents, withCredentials and credentials() for secrets, parameters for environment, browser and markers, the junit step and test trends, archiveArtifacts for traces and screenshots, publishHTML for pytest-html, the Allure plugin, parallel stages per browser, cron triggers, timeouts and post conditions, and Windows agents with bat.
🏗️ Jenkins Pipeline Basics
A pipeline is defined in a file called Jenkinsfile at the root of your repository. Jenkins reads it when you create a Pipeline (or Multibranch Pipeline) job pointing at the repository.
pipeline {
agent { ... } // where it runs
parameters { ... } // inputs shown on "Build with Parameters"
stages {
stage('Test') {
steps { ... } // shell commands and plugin steps
}
}
post { ... } // always / failure / success actions
}
Plugins used in this lesson (all common on Jenkins servers): Pipeline, Docker Pipeline, Credentials Binding, JUnit, HTML Publisher and (optionally) Allure.
📦 The Project
The same project shape as in Lesson 66:
📄 requirements.txt
playwright==1.65.2
pytest==9.2.0
pytest-playwright==0.10.0
pytest-base-url==2.1.0
pytest-html==4.2.0
pytest-xdist==3.8.0
📄 pytest.ini
[pytest]
addopts = --base-url https://sqatools.in
markers =
smoke: quick checks
📄 tests/test_shop.py
import os
import pytest
from playwright.sync_api import Page, expect
@pytest.mark.smoke
def test_home(page: Page):
page.goto("/dummy-ecommerce-website/")
expect(page.get_by_test_id("product-card").first).to_be_visible()
@pytest.mark.smoke
def test_login(page: Page):
page.goto("/dummy-ecommerce-website/#/login")
page.get_by_test_id("login-username").fill(os.getenv("SHOP_USER", "testuser"))
page.get_by_test_id("login-password").fill(os.getenv("SHOP_PASSWORD", "Test@123"))
page.get_by_test_id("login-button").click()
expect(page.get_by_test_id("account-button")).to_contain_text("Hi,")
📝 The Jenkinsfile
📄 Jenkinsfile
pipeline {
agent {
docker {
image 'mcr.microsoft.com/playwright/python:v1.65.2-noble'
args '--ipc=host'
}
}
parameters {
choice(name: 'BROWSER', choices: ['chromium', 'firefox', 'webkit'], description: 'Browser to test')
string(name: 'MARKERS', defaultValue: 'smoke', description: 'pytest -m expression (empty = all tests)')
string(name: 'BASE_URL', defaultValue: 'https://sqatools.in', description: 'Environment under test')
}
triggers {
cron('H 2 * * *') // nightly, at a spread-out minute in the 02:00 hour
}
options {
timeout(time: 45, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '30'))
timestamps()
}
environment {
PIP_DISABLE_PIP_VERSION_CHECK = '1'
SHOP = credentials('sqa-shop-user') // creates SHOP_USR and SHOP_PSW
}
stages {
stage('Install') {
steps {
sh 'python -m venv .venv'
sh '. .venv/bin/activate && pip install -r requirements.txt'
}
}
stage('Test') {
steps {
sh '''
. .venv/bin/activate
export SHOP_USER="$SHOP_USR" SHOP_PASSWORD="$SHOP_PSW"
pytest ${MARKERS:+-m "$MARKERS"} \
--browser "$BROWSER" --base-url "$BASE_URL" -n 2 \
--tracing retain-on-failure --screenshot only-on-failure \
--junitxml=reports/junit.xml \
--html=reports/report.html --self-contained-html
'''
}
}
}
post {
always {
junit allowEmptyResults: true, testResults: 'reports/junit.xml'
publishHTML(target: [reportDir: 'reports', reportFiles: 'report.html',
reportName: 'Playwright report', keepAll: true, alwaysLinkToLastBuild: true,
allowMissing: true])
}
failure {
archiveArtifacts artifacts: 'test-results/**', allowEmptyArchive: true
}
}
}
What each part does:
| Part | Purpose |
|---|---|
agent { docker { image ... } } |
Runs every step inside Microsoft’s Playwright Python image: Python, all browsers and their system libraries are already there. Match the tag to your playwright version |
args '--ipc=host' |
Recommended by Playwright for Chromium in Docker; avoids crashes from the small default shared memory |
parameters |
“Build with Parameters” form: browser, markers and environment without editing code |
cron('H 2 * * *') |
Nightly run; H lets Jenkins pick a minute to spread load across jobs |
timeout, buildDiscarder, timestamps |
Stops hung builds, keeps 30 builds, adds times to the log |
credentials('sqa-shop-user') |
Reads a Username with password credential and exposes SHOP_USR / SHOP_PSW, masked in the log |
${MARKERS:+-m "$MARKERS"} |
Shell trick: adds -m ... only when the parameter is not empty |
junit |
Records results; Jenkins draws pass/fail trends across builds and shows each failure |
publishHTML |
Adds a “Playwright report” link to the build page (HTML Publisher plugin) |
archiveArtifacts on failure |
Keeps traces, screenshots and videos only for failed builds |
📌 Note: The image already contains the browsers, so the pipeline never runs playwright install. The virtual environment is still useful: it installs your pinned test dependencies without touching the image’s own Python packages.
What the Test stage runs
The pipeline only orchestrates; the command is the same one you run locally, which is the key to debuggable CI:
⌨️ Terminal
pytest -m smoke --browser chromium --base-url https://sqatools.in -n 2 --tracing retain-on-failure --screenshot only-on-failure --junitxml=reports/junit.xml --html=reports/report.html --self-contained-html
🖥️ Output
bringing up nodes...
bringing up nodes...
.. [100%]
- Generated html report: file:///C:/Users/you/playwright-python/reports/report.html -
2 passed in 3.92s
['junit.xml', 'report.html']
Both files the post section expects exist: junit.xml for the junit step and report.html for publishHTML.
🔐 Credentials
Create the credential once: Manage Jenkins → Credentials → (global) → Add Credentials → Username with password, ID sqa-shop-user. Two ways to use it:
// 1. In environment {}: for the whole pipeline (as above)
SHOP = credentials('sqa-shop-user') // SHOP_USR, SHOP_PSW
// 2. Only around the step that needs it
withCredentials([usernamePassword(credentialsId: 'sqa-shop-user',
usernameVariable: 'SHOP_USER',
passwordVariable: 'SHOP_PASSWORD')]) {
sh '. .venv/bin/activate && pytest -m smoke'
}
Use single-quoted Groovy strings (sh '...') so the shell, not Groovy, expands $SHOP_PASSWORD. Double-quoted Groovy strings interpolate secrets into the command text, and Jenkins warns about it.
🧭 Parallel Browsers
Run each browser in its own stage, in parallel, with separate result files:
stage('Cross-browser') {
parallel {
stage('Chromium') { steps { sh '. .venv/bin/activate && pytest --browser chromium --junitxml=reports/junit-chromium.xml' } }
stage('Firefox') { steps { sh '. .venv/bin/activate && pytest --browser firefox --junitxml=reports/junit-firefox.xml' } }
stage('WebKit') { steps { sh '. .venv/bin/activate && pytest --browser webkit --junitxml=reports/junit-webkit.xml' } }
}
}
and record all of them with junit 'reports/junit-*.xml'. Add failFast false (the default) so one browser’s failure does not abort the others.
📈 Allure in Jenkins
With the Allure Jenkins plugin (and the Allure command-line tool configured under Manage Jenkins → Tools), add allure-pytest to the requirements, run pytest with --alluredir=allure-results and publish:
post {
always {
allure includeProperties: false, results: [[path: 'allure-results']]
}
}
The plugin generates the report on the server and keeps history and trends between builds automatically (Lesson 64 covers Allure itself).
🪟 Plain and Windows Agents
Without Docker, the agent needs Python and the browsers installed. On Linux add a browser install stage (playwright install --with-deps chromium, which needs root, so many teams pre-install browsers on the agent image). On a Windows agent use bat and the Windows venv layout:
stage('Install') {
steps {
bat 'python -m venv .venv'
bat '.venv\\Scripts\\pip install -r requirements.txt'
bat '.venv\\Scripts\\playwright install chromium msedge'
}
}
stage('Test') {
steps {
bat '.venv\\Scripts\\pytest -m smoke --browser-channel msedge --junitxml=reports\\junit.xml'
}
}
Backslashes are escaped (\\) inside Groovy strings. A Windows agent is the natural place for real Edge (--browser-channel msedge) runs.
🧯 Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Executable doesn't exist at .../ms-playwright/... |
Image or installed browsers don’t match the Playwright version | Align the image tag (or rerun playwright install) with requirements.txt |
| Chromium crashes in Docker | Small /dev/shm |
args '--ipc=host' (or --shm-size=1gb) |
junit step finds no files |
Tests did not run or wrong path | Check the pytest step’s output; use allowEmptyResults only intentionally |
| HTML report shows no styles | Jenkins’ Content Security Policy blocks inline CSS/JS | --self-contained-html still needs a relaxed CSP for scripts; ask your Jenkins admin, or rely on JUnit and artifacts |
| Build hangs | A test waits forever, no timeout | options { timeout(...) } and sensible Playwright timeouts |
🏋️ Practice Exercises
Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.
Exercise 1: Add a boolean parameter HEADED_DEBUG (default false) that, when true, adds --tracing on instead of retain-on-failure.
Show answer
parameters {
booleanParam(name: 'HEADED_DEBUG', defaultValue: false, description: 'Keep traces for every test')
}
...
sh '''
. .venv/bin/activate
if [ "$HEADED_DEBUG" = "true" ]; then TRACING=on; else TRACING=retain-on-failure; fi
pytest --tracing "$TRACING" --junitxml=reports/junit.xml
'''(A real headed browser makes no sense on a CI agent without a display; traces for every test are the CI equivalent.)
Exercise 2: Why should the junit step be in post { always { ... } } and not after pytest in the same stage?
Show answer
When tests fail, pytest exits with a non-zero code, the sh step fails and the stage stops, so a junit step placed after it would never run. In post { always } it runs regardless, recording failures (and Jenkins marks the build UNSTABLE or FAILED accordingly).
Exercise 3: Write a withCredentials block that exposes an API token stored as a Secret text credential with ID practice-api-token as API_TOKEN to one pytest call.
Show answer
withCredentials([string(credentialsId: 'practice-api-token', variable: 'API_TOKEN')]) {
sh '. .venv/bin/activate && pytest tests/api'
}The tests read it with os.environ["API_TOKEN"].
Exercise 4: Your Docker-based pipeline fails with “Executable doesn’t exist” after someone upgraded playwright to 1.66 in requirements.txt. What exactly do you change?
Show answer
The image tag: mcr.microsoft.com/playwright/python:v1.66.x-noble (the same version as the playwright package). Each Playwright release expects its own browser builds, and the old image contains the builds for 1.65.2.
🧠 MCQ Quiz: Playwright Python in Jenkins
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- Where is a Jenkins pipeline usually defined?Answer: In a
Jenkinsfileat the root of the repository. Pipeline-as-code keeps the pipeline versioned with the tests. - Why use the
mcr.microsoft.com/playwright/pythonimage as the agent?Answer: It already contains Python, the browsers and their system libraries. No browser installation step is needed, and versions are consistent. - What does
credentials('sqa-shop-user')create for a Username with password credential namedSHOP?Answer:SHOP_USRandSHOP_PSW(andSHOPas user:password). The environment directive binds the credential to<NAME>_USRand<NAME>_PSW. - Why use single-quoted strings for
shsteps that use secrets?Answer: The shell expands the variables at runtime instead of Groovy interpolating secrets into the command. Groovy interpolation would put the secret into the command text, which Jenkins warns about. - What does the
junitstep give you?Answer: Test results per build and trend charts across builds. The JUnit plugin parses the XML and tracks results over time. - Where should
junitbe placed so failures are still recorded?Answer: Inpost { always { ... } }. A failing pytest step stops the stage;post alwaysruns anyway. - What does
cron('H 2 * * *')mean?Answer: Once a day in the 02:00 hour, at a minute Jenkins chooses.Hspreads start times to avoid all jobs starting at the same minute. - Which Docker argument helps Chromium run reliably in a container?Answer:
--ipc=host. Chromium uses shared memory heavily; the default/dev/shmis small. - How do you run browsers in parallel in a declarative pipeline?Answer: A stage with a
parallel { stage(...) ... }block. The parallel block runs sibling stages at the same time. - What is a symptom of an image tag that does not match the installed
playwrightversion?Answer: “Executable doesn’t exist” errors for the browser. Playwright looks for the browser builds of its own version.
Want a longer, timed test? Take the Module 12 mock interview (20 MCQs in 20 minutes).
❓ Frequently Asked Questions
🤔 Jenkins or GitHub Actions?
Both run the same pytest command. GitHub Actions is simplest when code lives on GitHub; Jenkins suits companies with self-hosted infrastructure, private networks and existing Jenkins expertise. Keep your test command in one script or Makefile so switching is easy.
🤔 Can Jenkins show the Playwright trace?
Not directly. Archive test-results/** and open the downloaded trace with playwright show-trace or trace.playwright.dev (Lesson 62).
🤔 How do I run tests on every pull request?
Use a Multibranch Pipeline job (or GitHub/GitLab branch source plugins). Jenkins discovers branches and pull requests and runs the Jenkinsfile for each, reporting status back to the pull request.
🤔 Do I need pytest-xdist on Jenkins?
Not required, but -n with the agent’s CPU count (Lesson 65) shortens builds. Combine with parallel stages for browsers when agents have enough CPU and memory.
🤔 Why is the HTML report blank in Jenkins?
Jenkins’ default Content Security Policy blocks the JavaScript that pytest-html needs. Administrators can relax it for the HTML Publisher, or the team can rely on the JUnit results and the archived report file.
🏁 Summary
- A declarative
Jenkinsfilewith a Docker agent onmcr.microsoft.com/playwright/python:<version>needs no browser installation; match the tag to your Playwright version. - Pass secrets with
credentials()orwithCredentials, in single-quotedshstrings; drive runs with parameters and nightlycron. - Record results with
junitand reports withpublishHTMLor the Allure plugin inpost { always }; archivetest-results/**on failure. - Run browsers in
parallelstages, add timeouts, and usebatwith the Windows venv layout on Windows agents. - Keep the pytest command identical to local runs so CI failures are easy to reproduce.
🎬 Watch the Playwright tutorial series on YouTube!
Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page