{"id":21029883,"url":"https://github.com/kitconcept/jenkins-pipeline-examples","last_synced_at":"2025-04-06T04:15:35.518Z","repository":{"id":45299723,"uuid":"63760883","full_name":"kitconcept/jenkins-pipeline-examples","owner":"kitconcept","description":"Jenkins Pipeline Examples (by kitconcept)","archived":false,"fork":false,"pushed_at":"2022-12-21T11:46:06.000Z","size":111,"stargazers_count":210,"open_issues_count":6,"forks_count":242,"subscribers_count":15,"default_branch":"master","last_synced_at":"2025-03-30T03:08:48.098Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://kitconcept.com","language":"Shell","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kitconcept.png","metadata":{"files":{"readme":"README.rst","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-07-20T07:38:04.000Z","updated_at":"2024-12-02T16:40:46.000Z","dependencies_parsed_at":"2023-01-30T03:31:03.599Z","dependency_job_id":null,"html_url":"https://github.com/kitconcept/jenkins-pipeline-examples","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kitconcept%2Fjenkins-pipeline-examples","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kitconcept%2Fjenkins-pipeline-examples/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kitconcept%2Fjenkins-pipeline-examples/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kitconcept%2Fjenkins-pipeline-examples/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kitconcept","download_url":"https://codeload.github.com/kitconcept/jenkins-pipeline-examples/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247430964,"owners_count":20937875,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-19T12:14:53.525Z","updated_at":"2025-04-06T04:15:35.432Z","avatar_url":"https://github.com/kitconcept.png","language":"Shell","funding_links":[],"categories":[],"sub_categories":[],"readme":"Jenkins Pipeline Examples (by kitconcept)\n==============================================================================\n\nOptions\n-------\n\nDisable concurrent builds::\n\n  pipeline {\n\n    agent any\n\n    options {\n      disableConcurrentBuilds()\n    }\n    ...\n  }\n\nSet global timeout::\n\n  options {\n    timeout(time: 30, unit: 'MINUTES')\n  }\n\nDiscard old builds and artifacts::\n\n  options {\n    buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '30'))\n  }\n\nParameters\n----------\n\nJenkins allows to ask the user for job paremeters before the job execution.\nPossible parameters are boolean, choice, file, text, password, run, or string::\n\n  pipeline {\n      agent any\n\n      parameters {\n          booleanParam(defaultValue: true, description: '', name: 'booleanExample')\n          string(defaultValue: \"TEST\", description: 'What environment?', name: 'stringExample')\n          text(defaultValue: \"This is a multiline\\n text\", description: \"Multiline Text\", name: \"textExample\")\n          choice(choices: 'US-EAST-1\\nUS-WEST-2', description: 'What AWS region?', name: 'choiceExample')\n          password(defaultValue: \"Password\", description: \"Password Parameter\", name: \"passwordExample\")\n      }\n\n      stages {\n          stage(\"my stage\") {\n              steps {\n                  echo \"booleanExample: ${params.booleanExample}\"\n                  echo \"stringExample: ${params.stringExample}\"\n                  echo \"textExample: ${params.textExample}\"\n                  echo \"choiceExample: ${params.choiceExample}\"\n                  echo \"passwordExample: ${params.passwordExample}\"\n              }\n          }\n      }\n  }\n\nTriggers / Scheduling\n---------------------\n\nTrigger build regularly with cron::\n\n  pipeline {\n      agent any\n      triggers {\n          cron('H */4 * * 1-5')\n      }\n      stages {\n          stage('Example') {\n              steps {\n                  echo 'Hello World'\n              }\n          }\n      }\n  }\n\nTriggers Pipeline Syntax docs: `https://jenkins.io/doc/book/pipeline/syntax/#triggers`_.\n\nParemeterized Trigger / Cron::\n\n  pipeline {\n      agent any\n      parameters {\n        string(name: 'PLANET', defaultValue: 'Earth', description: 'Which planet are we on?')\n        string(name: 'GREETING', defaultValue: 'Hello', description: 'How shall we greet?')\n      }\n      triggers {\n          cron('* * * * *')\n          parameterizedCron('''\n  # leave spaces where you want them around the parameters. They'll be trimmed.\n  # we let the build run with the default name\n  */2 * * * * %GREETING=Hola;PLANET=Pluto\n  */3 * * * * %PLANET=Mars\n          ''')\n      }\n      stages {\n          stage('Example') {\n              steps {\n                  echo \"${GREETING} ${PLANET}\"\n                  script { currentBuild.description = \"${GREETING} ${PLANET}\" }\n              }\n          }\n      }\n  }\n\nGit Checkout\n------------\n\nGit Checkout::\n\n  checkout scm\n\nThe Jenkinsfile job configuration already contains the repository URL. Therefore a checkout is as simple as that. See `this \u003chttp://stackoverflow.com/questions/38198878/jenkins-pipeline-build-github-pull-request#answer-38212467\u003e`_ for details.\n\n\nClean Workspace\n---------------\n\nClean workspace::\n\n  deleteDir()\n\nSee `Jenkins workflow basic steps docs \u003chttps://jenkins.io/doc/pipeline/steps/workflow-basic-steps/#code-deletedir-code-recursively-delete-the-current-directory-from-the-workspace\u003e`_ for more details.\n\n\nPipeline / Distributed Build\n----------------------------\n\nJenkins allows to create pipeline steps that are automatically distributed across the available nodes.\n\nCreate pipeline steps::\n\n  stage('Build') {\n    node {\n      ...\n    }\n  }\n\n  stage('Test') {\n    node {\n      ...\n    }\n  }\n\nStash/Unstash\n^^^^^^^^^^^^^\n\nUse stash/unstash to share data between pipelines::\n\n  stage('Build') {\n    node {\n      checkout scm\n      sh \"npm install\"\n      stash includes: 'node_modules/', name: 'node_modules'\n    }\n  }\n\n  stage('Test') {\n    node {\n      unstash 'node_modules'\n      sh \"npm run test\"\n    }\n  }\n\nThe 'Build' pipeline step checks out the repository and runs 'npm install'. The build artifacts in 'node_modules' are stashed for later pipeline steps to be used.\n\nThe 'Test' pipeline steps unstashes the 'node_modules' stash (lookup by name) and allows to use it (e.g. to run tests on the installed modules).\n\nNote that files are discarded at the end of the build. If you want to keep the artifacts use 'stash/unstash'.\n\nArtifacts\n^^^^^^^^^\n\nArchive artifacts at the end of the job::\n\n    post {\n        always {\n            archiveArtifacts artifacts: 'build/libs/**/*.jar', fingerprint: true, allowEmptyArchive: true\n        }\n   }\n\n\"allowEmptyArchive: true\" makes the build not fail when no artifacts are found. \"fingerprint: true\" allows to track artifacts over nodes.\n\nClean Workspace\n^^^^^^^^^^^^^^^\n\nIn order to start with a clean build it is essential to clear the workspace before a checkout or an unstash::\n\n  stage('Build') {\n    node {\n      deleteDir()\n      checkout scm\n      sh \"npm install\"\n      stash includes: 'node_modules/', name: 'node_modules'\n    }\n  }\n\n  stage('Test') {\n    node {\n      deleteDir()\n      unstash 'node_modules'\n      sh \"npm run test\"\n    }\n  }\n\nWhen dealing with build artifacts with lots of file (e.g. node_modules or buildout) stashing/unstashing can take quite a while.\n\n\nDeclarative Pipeline\n--------------------\n\nCloudbees announced a new declarative pipeline syntax in December 2016:\n\nhttps://jenkins.io/blog/2016/12/19/declarative-pipeline-beta/?utm_source=feedburner\u0026utm_medium=twitter\u0026utm_campaign=Feed%3A+ContinuousBlog+%28Jenkins%29\n\nhttps://github.com/jenkinsci/pipeline-model-definition-plugin/wiki/getting%20started\n\nhttps://github.com/jenkinsci/pipeline-model-definition-plugin/blob/master/SYNTAX.md\n\nThis allows to write a cleaner pipeline::\n\n  #!groovy\n  pipeline {\n    stages {\n      stage('Build') {\n        node {\n          checkout scm\n        }\n      }\n\n      stage('Static Code Analysis') {\n        node() {\n          sh \"echo 'Run Static Code Analysis'\"\n        }\n      }\n\n      stage('Unit Tests') {\n        node() {\n          sh \"echo 'Run Tests'\"\n        }\n      }\n\n      stage('Acceptance Tests') {\n        node() {\n          sh \"echo 'Run Acceptance Tests'\"\n        }\n      }\n    }\n    post {\n      always {\n        deleteDir()\n      }\n      success {\n        mail to:\"me@example.com\", subject:\"SUCCESS: ${currentBuild.fullDisplayName}\", body: \"Yay, we passed.\"\n      }\n      failure {\n        mail to:\"me@example.com\", subject:\"FAILURE: ${currentBuild.fullDisplayName}\", body: \"Boo, we failed.\"\n      }\n    }\n  }\n\nDeclarative Pipeline Post Actions (global)::\n\n  #!groovy\n  pipeline {\n    stages {\n      ...\n    }\n    post {\n      // always means, well, always run.\n      always {\n        echo \"Hi there\"\n      }\n      // changed means when the build status is different than the previous build's status.\n      changed {\n        echo \"I'm different\"\n      }\n      // success, failure, unstable all run if the current build status is successful, failed, or unstable, respectively\n      success {\n        echo \"I succeeded\"\n        archive \"**/*\"\n      }\n    }\n  }\n\nDeclarative Pipeline Post Actions (stage)::\n\n  #!groovy\n  pipeline {\n    stages {\n      stage(\"first stage\") {\n        when { ... }\n        post {\n          // always means, well, always run.\n          always {\n            echo \"Hi there\"\n          }\n          // changed means when the build status is different than the previous build's status.\n          changed {\n            echo \"I'm different\"\n          }\n          // success, failure, unstable all run if the current build status is successful, failed, or unstable, respectively\n          success {\n            echo \"I succeeded\"\n            archive \"**/*\"\n          }\n        }\n      }\n    }\n  }\n\nPost action docs: https://github.com/jenkinsci/pipeline-model-definition-plugin/wiki/Syntax-Reference\n\nDeclarative Pipeline Parallel Build Steps::\n\n  // --- STATIC CODE ANALYSIS ---\n  stage('Static Code Analysis') {\n    parallel {\n      stage('Backend') {\n        agent {\n          label \"node\"\n        }\n        steps {\n          sh \"ls -al\"\n          }\n        }\n      }\n      stage('Frontend') {\n        agent {\n          label \"node\"\n        }\n        steps {\n            sh \"ls -al\"\n          }\n        }\n      }\n    }\n  }\n\n\nTest Results\n------------\n\nInclude jUnit-based test results::\n\n  sh \"bin/test\"\n  step([\n    $class: 'JUnitResultArchiver',\n    testResults: 'parts/test/testreports/*.xml'\n  ])\n\n\nEmail Notifications\n-------------------\n\nSend email notifications::\n\n  emailext (\n    to: 'info@kitconcept.com',\n    subject: \"${env.JOB_NAME} #${env.BUILD_NUMBER} [${currentBuild.result}]\",\n    body: \"Build URL: ${env.BUILD_URL}.\\n\\n\",\n    attachLog: true,\n  )\n\nSend email notifications to build requester and/or committers since last successful build::\n\n  emailext (\n    subject: \"FAILURE: #${env.BUILD_NUMBER} ${env.JOB_NAME}\",\n    body: \"Hey, it seems one of your recent commits broke the build, please check ${env.BUILD_URL}.\",\n    attachLog: true,\n    recipientProviders: [[$class: 'RequesterRecipientProvider'], [$class:'CulpritsRecipientProvider']]\n  )\n      \nRequires `Email-ext Plugin \u003chttps://wiki.jenkins-ci.org/display/JENKINS/Email-ext+plugin\u003e`_.\n\nSlack Notifications\n-------------------\n\nAdd Slack notification::\n\n  slackSend channel: '#general', color: 'good', message: '[${currentBuild.result}] #${env.BUILD_NUMBER} ${env.BUILD_URL}', teamDomain: 'kitconcept', token: '\u003cADD-TOKEN-HERE\u003e'\n\nTutorial how to set up Jenkins and Slack: https://medium.com/appgambit/integrating-jenkins-with-slack-notifications-4f14d1ce9c7a\n\nRobot Framework\n---------------\n\nPublish Robot Framework test results::\n\n  sh \"pybot tests/acceptance\"\n  step([$class: 'RobotPublisher',\n    disableArchiveOutput: false,\n    logFileName: 'log.html',\n    otherFiles: '',\n    outputFileName: 'output.xml',\n    outputPath: '.',\n    passThreshold: 100,\n    reportFileName: 'report.html',\n    unstableThreshold: 0]);\n\nRequires `Robot Framework Plugin \u003chttps://wiki.jenkins-ci.org/display/JENKINS/Robot+Framework+Plugin\u003e`_.\n\nRunning Robot Framework test with Selenium requires wrapping the test execution into an Xvfb wrapper::\n\n  wrap([$class: 'Xvfb']) {\n    sh \".env/bin/pybot tests/acceptance\"\n    step([$class: 'RobotPublisher',\n      disableArchiveOutput: false,\n      logFileName: 'log.html',\n      otherFiles: '',\n      outputFileName: 'output.xml',\n      outputPath: '.',\n      passThreshold: 100,\n      reportFileName: 'report.html',\n      unstableThreshold: 0]);\n  }\n\nRobot for Plone::\n\n  bin/test --all --xml\n  step([\n    $class: 'RobotPublisher',\n    disableArchiveOutput: false,\n    logFileName: 'robot_log.html',\n    onlyCritical: true,\n    otherFiles: '**/*.png',\n    outputFileName: 'robot_output.xml',\n    outputPath: 'parts/test',\n    passThreshold: 100,\n    reportFileName: 'robot_report.html',\n    unstableThreshold: 0\n  ]);\n\nPort Allocation\n---------------\n\nIn order to scale Jenkins, your builds need to be able to run in parallel. You can use containers to isolate the builds or allocate ports for each job/test run::\n\n  sh \".env/bin/pybot --variable PORT=\\$(python -c \\\"import socket; s = socket.socket(socket.AF_INET, socket.SOCK_STREAM); s.bind(('', 0)); print(s.getsockname()[1])\\\") tests/acceptance\"\n\nThe `Port Allocator Plugin \u003chttps://wiki.jenkins-ci.org/display/JENKINS/Port+Allocator+Plugin\u003e`_ is currently not compatible with pipeline jobs. Therefore we use a simple Python script to do the trick (make sure you have a Python interpreter on your machine).\n\n\nStatic Code Analysis\n--------------------\n\nPep8/Flake8:\n\n  timeout(time: 5, unit: 'MINUTES') {\n    sh 'bin/code-analysis'\n    step([$class: 'WarningsPublisher',\n      parserConfigurations: [[\n        parserName: 'Pep8',\n        pattern: 'parts/code-analysis/flake8.log'\n      ]],\n      unstableTotalAll: '0',\n      usePreviousBuildAsReference: true\n    ])\n  }\n\nWe use the 'Pep8' parser and the pattern is the path to the log file created by either pep8 or flake8. 'unstableTotalAll' = 0 makes sure the build is marked unstable if there is a single violation. If you want the build to fail on violations, use \"failedTotalAll: '0'\". It is not recommended to use any other threshold than '0' for those settings.\n\nTSLint::\n\n  timeout(time: 5, unit: 'MINUTES') {\n    sh 'npm run lint:ci'\n    step([$class: 'WarningsPublisher',\n      parserConfigurations: [[\n        parserName: 'JSLint',\n        pattern: 'pmd.xml'\n      ]],\n      unstableTotalAll: '0',\n      usePreviousBuildAsReference: true\n    ])\n  }\n\nRequires `Warnings Plugin \u003chttps://wiki.jenkins-ci.org/display/JENKINS/Warnings+Plugin\u003e`_.\n\nThere is no documentation whatsoever available of how to use this plugin with Jenkins pipelines. See this `github commit \u003chttps://github.com/jenkinsci/warnings-plugin/commit/ee546a8f9de5dab58925e883c413d34659519696\u003e`_. for details.\n\n\nLinting\n-------\n\nPublish ESLint report::\n\n  sh \"npm run lint\"\n  step([$class: 'CheckStylePublisher',\n    pattern: '**/eslint.xml',\n    unstableTotalAll: '0',\n    usePreviousBuildAsReference: true])\n\nRequires `Checkstyle Plugin \u003chttps://wiki.jenkins-ci.org/display/JENKINS/Checkstyle+Plugin\u003e`_.\n\nI used the `Violations Plugin \u003chttps://wiki.jenkins-ci.org/display/JENKINS/Violations\u003e` before but this plugin is not compatible with pipeline jobs and it seems it became unmaintained.\n\n\nHTML Reports\n------------\n\nPublish HTML::\n\n    publishHTML (target: [\n      allowMissing: false,\n      alwaysLinkToLastBuild: false,\n      keepAll: true,\n      reportDir: 'docs/_build',\n      reportFiles: 'index.html',\n      reportName: \"Developer Documentation\"\n    ])\n\nRequires `HTML Publisher Plugin \u003chttps://wiki.jenkins-ci.org/display/JENKINS/HTML+Publisher+Plugin\u003e`_.\n\nFor some reports, such as lighthouse you need to relax the content security policy in your /etc/default/jenkins file:\n\n```\nJAVA_ARGS=\"-Dhudson.model.DirectoryBrowserSupport.CSP=\\\"sandbox allow-scripts; default-src *; style-src * http://* 'unsafe-inline' 'unsafe-eval'; script-src 'self' http://* 'unsafe-inline' 'unsafe-eval'; img-src 'self' data:\\\"\"\n```\n\nCode Coverage\n-------------\n\nThe Cobertura plugin is not there yet:\n\nhttps://github.com/jenkinsci/cobertura-plugin/issues/50\n\nYou can use the HTML publisher plugin instead though.\n\n\nTimeouts\n--------\n\nTests or build steps are sometimes stuck because of issues beyond our control. Therefore it makes sense to kill a build if it is stuck. For traditional Jenkins jobs there is the `Build-timeout Plugin \u003chttps://wiki.jenkins-ci.org/display/JENKINS/Build-timeout+Plugin\u003e`_. Though, pipelines give us a far more fine-grained control::\n\n  timeout(time: 5, unit: 'MINUTES') {\n    ...\n  }\n\n\nLock Resources\n--------------\n\nLock a resource that requires exclusive access::\n\n  lock('my-resource-name') {\n    echo 'Do something here that requires unique access to the resource'\n    // any other build will wait until the one locking the resource leaves this block\n  }\n\nRequires `Lockable Resources Plugin \u003chttps://wiki.jenkins-ci.org/display/JENKINS/Lockable+Resources+Plugin\u003e`_.\n\nLock multiple stages in a declarative pipeline::\n\n  stage('Parent') {\n    options {\n      lock('myLock')\n    }\n    stages {\n      stage('first child') {\n        ...\n      }\n      stage('second child') {\n        ...\n      }\n    }\n  }\n\nNOT THERE YET! https://issues.jenkins-ci.org/browse/JENKINS-43336\n\nIcons/Badges\n------------\n\nThe  `Groovy Postbuild Plugin \u003chttps://wiki.jenkins-ci.org/display/JENKINS/Groovy+Postbuild+Plugin\u003e`_ allows to annotate builds with icons or badges. E.g. add a version badge to the build::\n\n  version=readFile('uxf/dist/uxf/version.txt')\n  manager.addShortText(\"${version}\")\n\nAdd warnings badge to the build::\n\n  manager.addWarningBadge(\"Deployment to portal.vnc.biz failed!\")\n\nAdd warning message to the detailed build view::\n\n  manager.createSummary(\"warning.gif\").appendText(\"\u003ch1\u003eDeployment to portal.vnc.biz failed!\u003c/h1\u003e\", false, false, false, \"red\")\n\nGroovy Variables\n----------------\n\nLoad file content into Groovy variable::\n\n  version=readFile('src/client/version.txt')\n\nUse Groovy variable::\n\n  currentBuild.description = 'VNCuxf Mail (${version})'\n\nDeclarative Pipeline::\n\n  script {\n    VERSION = sh(\n      script: 'cat package.json | python -c \"import sys, json; print json.load(sys.stdin)[\\'version\\']\"',\n      returnStdout: true\n  ).trim()\n\n  sh \"echo VERSION\"\n  sh \"echo ${VERSION}\"\n\nDeclarative Pipeline (ignore exit code)::\n\n  script {\n    psiExitCode = sh(\n      script: 'yarn run psi',\n      returnStdout: true,\n      returnStatus: true\n    )\n  }\n\n\nGlobal Variables\n----------------\n\nCurrent Build::\n\n  currentBuild.result\n  currentBuild.displayName\n  currentBuild.description\n\nEnvironment::\n\n  env.path\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkitconcept%2Fjenkins-pipeline-examples","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkitconcept%2Fjenkins-pipeline-examples","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkitconcept%2Fjenkins-pipeline-examples/lists"}