This Jenkins cheat sheet collects the syntax testers use most: a complete Jenkinsfile for running an automation suite, the declarative pipeline blocks, cron schedules, parameters, built-in environment variables, post-build actions and the CLI. Bookmark it for when you're writing or debugging a pipeline.

📌 On this page
  • A ready-to-use Jenkinsfile for a Maven + TestNG test suite
  • Declarative pipeline syntax: agent, tools, parameters, environment, triggers, options, stages, post
  • Cron schedules (and what H means)
  • Parallel stages, conditions, retries and built-in variables
  • Jenkins CLI commands and useful URLs

A Complete Jenkinsfile for Test Automation

Put this file named Jenkinsfile in the root of your test project, then create a Pipeline job that reads it from Git ("Pipeline script from SCM"):

pipeline {
    agent any

    tools {
        maven 'Maven-3'          // names as configured in Manage Jenkins → Tools
        jdk 'JDK-21'
    }

    parameters {
        choice(name: 'BROWSER', choices: ['chrome', 'firefox', 'edge'], description: 'Browser to test')
        string(name: 'ENV', defaultValue: 'qa', description: 'Environment')
        booleanParam(name: 'SMOKE_ONLY', defaultValue: false, description: 'Run only the smoke suite')
    }

    environment {
        BASE_URL = "https://${params.ENV}.example.com"
    }

    triggers {
        cron('H 2 * * 1-5')      // nightly regression, Monday–Friday around 02:00
    }

    options {
        timeout(time: 60, unit: 'MINUTES')
        buildDiscarder(logRotator(numToKeepStr: '20'))
    }

    stages {
        stage('Checkout') {
            steps { checkout scm }
        }
        stage('Test') {
            steps {
                sh "mvn -B clean test -Dbrowser=${params.BROWSER} -DbaseUrl=${env.BASE_URL} -Dgroups=${params.SMOKE_ONLY ? 'smoke' : 'regression'}"
            }
        }
    }

    post {
        always {
            junit 'target/surefire-reports/*.xml'
            archiveArtifacts artifacts: 'target/screenshots/**', allowEmptyArchive: true
        }
        failure {
            echo "Build ${env.BUILD_NUMBER} failed: ${env.BUILD_URL}"
        }
    }
}

It runs a Maven/TestNG suite with a chosen browser and environment, runs nightly on weekdays, keeps the last 20 builds, publishes the TestNG/JUnit results and archives screenshots.

Advertisement

Declarative Pipeline Syntax

BlockWhat it doesExample
agentWhere the pipeline runsagent any, agent { label 'linux' }, agent { docker { image 'maven:3.9-eclipse-temurin-21' } }
toolsPuts configured tools on the PATHmaven 'Maven-3', jdk 'JDK-21'
parametersInputs for "Build with Parameters"choice, string, booleanParam
environmentEnvironment variablesBASE_URL = "https://qa.example.com"
triggersAutomatic startscron('H 2 * * 1-5'), pollSCM('H/15 * * * *')
optionsJob settingstimeout(time: 60, unit: 'MINUTES'), buildDiscarder(logRotator(numToKeepStr: '20')), retry(2)
stages / stage / stepsThe work, in named stagesstage('Test') { steps { sh 'mvn test' } }
whenRun a stage only if…when { branch 'main' }, when { expression { params.SMOKE_ONLY } }
postAfter the buildalways, success, failure, unstable, changed

Run Browsers in Parallel

stage('Cross-browser') {
    parallel {
        stage('Chrome')  { steps { sh 'mvn -B test -Dbrowser=chrome' } }
        stage('Firefox') { steps { sh 'mvn -B test -Dbrowser=firefox' } }
    }
}

Cron Schedules in Jenkins

Five fields: minute hour day-of-month month day-of-week. H ("hash") lets Jenkins pick a fixed but spread-out value for each job, so not every job starts at exactly the same minute.

ScheduleMeans
H 2 * * *Every day around 02:00
H 2 * * 1-5Monday to Friday around 02:00
H/15 * * * *About every 15 minutes
H 9-17/2 * * 1-5Every 2 hours from 09:00 to 17:00 on weekdays
@daily, @midnight, @hourlyShortcuts (Jenkins spreads them with H)

Built-in Environment Variables

VariableValue
BUILD_NUMBERThe build number, e.g. 42
BUILD_URLLink to this build
JOB_NAMEName of the job
WORKSPACEFolder where the code is checked out
BRANCH_NAMEBranch being built (multibranch pipelines)
GIT_COMMITCommit being built (with the Git plugin)

Use them as ${env.BUILD_NUMBER} inside double-quoted strings. The full list for your server is at <jenkins-url>/env-vars.html.

Useful Steps for Testers

StepUse
sh '…' / bat '…'Run a command on Linux/macOS or Windows agents
junit 'target/surefire-reports/*.xml'Publish test results and trends
archiveArtifactsKeep screenshots, logs or reports with the build
retry(2) { … }Retry a flaky step
timeout(time: 10, unit: 'MINUTES') { … }Stop a hanging step
catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') { … }Mark a stage failed but keep the pipeline going
input 'Deploy to staging?'Wait for a human approval

Jenkins CLI and Useful URLs

# download jenkins-cli.jar from <jenkins-url>/jnlpJars/jenkins-cli.jar
java -jar jenkins-cli.jar -s http://localhost:8080 -auth user:API_TOKEN list-jobs
java -jar jenkins-cli.jar -s http://localhost:8080 -auth user:API_TOKEN build Regression -p BROWSER=firefox -s -v
java -jar jenkins-cli.jar -s http://localhost:8080 -auth user:API_TOKEN safe-restart
URLWhat it shows
/pipeline-syntaxSnippet Generator — builds step syntax for you
/env-vars.htmlAll built-in environment variables
/manageManage Jenkins (tools, plugins, credentials, nodes)
/safeRestartRestart after running builds finish

Common Mistakes

  1. Single quotes around variables: sh 'echo ${params.BROWSER}' passes the text literally to the shell. Use double quotes for Groovy variables: sh "echo ${params.BROWSER}".
  2. Tests fail but the build is green: make sure Maven actually fails (don't add -Dmaven.test.failure.ignore=true unless you publish results with junit, which marks the build unstable).
  3. Every job scheduled at 0 2 * * *: all jobs start at the same second. Use H 2 * * *.
  4. Passwords in the Jenkinsfile: store them under Credentials and use withCredentials or credentials('id').
  5. No timeout: a stuck browser can block an agent for hours. Always set options { timeout(...) }.

📚 Official documentation: Jenkins: Pipeline syntax · Jenkins CLI

Frequently Asked Questions

What does H mean in Jenkins cron?

H (hash) makes Jenkins choose a consistent value for each job within the range, spreading jobs out so they don't all start at once. H 2 * * * means "once around 2 AM".

Where do I put the Jenkinsfile?

In the root of your Git repository. Create a Pipeline job and choose "Pipeline script from SCM" so Jenkins reads it from the repository.

How do I pass parameters to a Jenkins pipeline?

Declare them in a parameters block and read them as params.NAME. Start the job with "Build with Parameters" or from the CLI with -p NAME=value.

How do I publish TestNG results in Jenkins?

TestNG writes JUnit-style XML to target/surefire-reports; publish it with junit 'target/surefire-reports/*.xml' in a post { always { } } block.

What is the difference between declarative and scripted pipeline?

Declarative uses the structured pipeline { } syntax shown here and is easier to read; scripted is plain Groovy inside node { }. Most teams use declarative.