Basics about .jenkins files

 about the top-level pipeline directives (like agent, triggers, environment, stages) in a .jenkins (i.e., Jenkins declarative pipeline) file, and what types of arguments/values they support, along with their use.

Here’s a cheat sheet for the most common directives and their argument types:


🔹 agent

Defines where the pipeline/stage runs.

Arguments / Types:

  • any → Run on any available agent.

  • none → No global agent (must define agent at stage level).

  • label 'my-label' → Run on agents with this label.

  • node { ... } → Advanced node selection.

  • docker { image 'maven:3-alpine' } → Run inside a Docker container.

  • dockerfile { filename 'Dockerfile' } → Build and run from a Dockerfile.

Use: Controls execution environment.


🔹 triggers

Defines automatic job triggers.

Arguments / Types:

  • cron('H 4/* 0 0 1-5') → Standard cron syntax (with Jenkins H helper for hash spread).

  • pollSCM('* * * * *') → Poll source control for changes.

  • upstream(upstreamProjects: 'job1,job2', threshold: hudson.model.Result.SUCCESS) → Trigger from another job.

Use: Schedule or event-based job starts.


🔹 environment

Defines environment variables available to the pipeline.

Arguments / Types:

  • Key-value pairs:

    environment { APP_ENV = 'prod' PATH = "/usr/local/bin:${env.PATH}" }
  • Can also use credentials:

    environment { AWS_CREDS = credentials('aws-cred-id') }

Use: Set environment variables/credentials globally or per stage.


🔹 parameters

Defines build-time input parameters.

Arguments / Types:

  • string(name: 'BRANCH', defaultValue: 'main', description: 'Git branch')

  • booleanParam(name: 'RUN_TESTS', defaultValue: true, description: 'Run tests?')

  • choice(name: 'ENV', choices: ['dev','qa','prod'], description: 'Environment')

  • password(name: 'SECRET')

Use: User inputs when triggering the job.


🔹 options

Special execution options.

Arguments / Types:

  • timeout(time: 1, unit: 'HOURS') → Job timeout.

  • buildDiscarder(logRotator(numToKeepStr: '10')) → Keep only last 10 builds.

  • disableConcurrentBuilds() → Prevent concurrent builds.

  • skipStagesAfterUnstable() → Skip later stages if build unstable.

Use: Fine-tune job behavior.


🔹 stages / stage

Defines pipeline steps.

Arguments / Types:

  • stage('Build') { steps { ... } } → Regular stage.

  • when { branch 'main' } → Conditional execution.

  • matrix { axes { ... } } → Run across multiple configurations.

Use: Main build/test/deploy steps.


🔹 post

Defines actions after build/stage completion.

Arguments / Types:

  • always { ... }

  • success { ... }

  • failure { ... }

  • unstable { ... }

  • changed { ... }

Use: Notifications, cleanup, archiving logs.


🔹 tools

Defines build tools to auto-install.

Arguments / Types:

  • maven 'Maven-3.8'

  • jdk 'Java-11'

  • gradle 'Gradle-7'

Use: Ensure specific tool versions are available.


✅ In short, the main directives & arguments you’ll use are:

  • agent (execution env: any, label, docker, dockerfile, none)

  • triggers (cron, pollSCM, upstream)

  • environment (vars, credentials)

  • parameters (string, boolean, choice, password, etc.)

  • options (timeout, discard builds, concurrency control)

  • stages (with when, matrix, steps)

  • post (success, failure, always, etc.)

  • tools (maven, jdk, gradle, etc.)



Example Groovy File:

pipeline {
    /**********************
     *  Agent Definition
     **********************/
    agent {
        // Run inside a Docker container (example: Maven build)
        docker {
            image 'maven:3.8.4-openjdk-11'
            args '-v /tmp:/tmp' // mount a volume
        }
    }

    /**********************
     *  Build Triggers
     **********************/
    triggers {
        cron('H 4 * * 1-5')              // Run Mon–Fri at 4am (distributed start with H)
        pollSCM('H/15 * * * *')          // Poll SCM every 15 mins
        upstream(upstreamProjects: 'upstream-job', threshold: hudson.model.Result.SUCCESS)
    }

    /**********************
     *  Environment Variables
     **********************/
    environment {
        APP_ENV = "production"
        PATH = "/usr/local/bin:${env.PATH}"
        AWS_CREDS = credentials('aws-credentials-id')
    }

    /**********************
     *  Input Parameters
     **********************/
    parameters {
        string(name: 'BRANCH', defaultValue: 'main', description: 'Git branch to build')
        booleanParam(name: 'RUN_TESTS', defaultValue: true, description: 'Run test suite?')
        choice(name: 'DEPLOY_ENV', choices: ['dev', 'qa', 'prod'], description: 'Deployment environment')
        password(name: 'SECRET_TOKEN', description: 'API token for deployment')
    }

    /**********************
     *  Build Options
     **********************/
    options {
        timeout(time: 1, unit: 'HOURS')               // Pipeline timeout
        buildDiscarder(logRotator(numToKeepStr: '10')) // Keep last 10 builds
        disableConcurrentBuilds()                      // Don’t allow concurrent runs
        skipStagesAfterUnstable()                      // Skip later stages if unstable
    }

    /**********************
     *  Tools
     **********************/
    tools {
        maven 'Maven-3.8'
        jdk 'Java-11'
    }

    /**********************
     *  Stages
     **********************/
    stages {
        stage('Checkout') {
            agent any
            steps {
                echo "Checking out branch: ${params.BRANCH}"
                checkout scm
            }
        }

        stage('Build') {
            when { branch 'main' } // only run on main branch
            steps {
                sh 'mvn clean package'
            }
        }

        stage('Test') {
            when { expression { return params.RUN_TESTS } }
            steps {
                sh 'mvn test'
            }
        }

        stage('Deploy') {
            matrix {
                axes {
                    axis {
                        name 'ENV'
                        values 'dev', 'qa', 'prod'
                    }
                }
                stages {
                    stage('Deploy Matrix') {
                        steps {
                            echo "Deploying to ${ENV} environment with secret: ${params.SECRET_TOKEN}"
                        }
                    }
                }
            }
        }
    }

    /**********************
     *  Post Actions
     **********************/
    post {
        always {
            echo 'Cleaning up workspace...'
            cleanWs()
        }
        success {
            echo 'Build succeeded ✅'
        }
        failure {
            echo 'Build failed ❌'
        }
        unstable {
            echo 'Build unstable ⚠️'
        }
        changed {
            echo 'Build status changed compared to previous run.'
        }
    }
}


Comments