Repository: dalalv/jenkinsfiles Branch: master Commit: 3612ab76556e Files: 19 Total size: 12.8 KB Directory structure: gitextract_yx4hh3xv/ ├── README.md ├── externalCall.groovy ├── externalMethod.groovy ├── flow.groovy ├── gitcommit.groovy ├── jenkinsfile-complex-promotion-model ├── jenkinsfile-conditional-os ├── jenkinsfile-credentials-binding ├── jenkinsfile-import-groovy-scripts ├── jenkinsfile-include-groovy-script ├── jenkinsfile-multiple-os-parallel ├── jenkinsfile-parallel-jobs ├── jenkinsfile-push-to-git-repo ├── jenkinsfile-set-env-vars ├── jenkinsfile-stash-unstash ├── jenkinsfile-timestamperWrapper ├── jenkinsfile-types-of-build-cause ├── slackNotify.groovy └── standardBuild.groovy ================================================ FILE CONTENTS ================================================ ================================================ FILE: README.md ================================================ # jenkinsfiles Examples collected for Jenkins files from www ================================================ FILE: externalCall.groovy ================================================ // If there's a call method, you can just load the file, say, as "foo", and then invoke that call method with foo(...) def call(String whoAreYou) { echo "Now we're being called more magically, ${whoAreYou}, thanks to the call(...) method." } ================================================ FILE: externalMethod.groovy ================================================ // Methods in this file will end up as object methods on the object that load returns. def lookAtThis(String whoAreYou) { echo "Look at this, ${whoAreYou}! You loaded this from another file!" } ================================================ FILE: flow.groovy ================================================ #!groovy // Orig Ref From :: https://documentation.cloudbees.com/docs/cookbook/_setting_up_a_basic_build_pipeline_with_jenkins.html def devQAStaging() { env.PATH="${tool 'Maven 3.x'}/bin:${env.PATH}" stage 'Dev' sh 'mvn clean install package' archive 'target/x.war' try { checkpoint('Archived war') } catch (NoSuchMethodError _) { echo 'Checkpoint feature available in Jenkins Enterprise by CloudBees.' } stage 'QA' parallel(longerTests: { runWithServer {url -> sh "mvn -f sometests/pom.xml test -Durl=${url} -Dduration=30" } }, quickerTests: { runWithServer {url -> sh "mvn -f sometests/pom.xml test -Durl=${url} -Dduration=20" } }) stage name: 'Staging', concurrency: 1 deploy 'target/x.war', 'staging' } def production() { input message: "Does http://localhost:8888/staging/ look good?" try { checkpoint('Before production') } catch (NoSuchMethodError _) { echo 'Checkpoint feature available in Jenkins Enterprise by CloudBees.' } stage name: 'Production', concurrency: 1 node { unarchive mapping: ['target/x.war' : 'x.war'] deploy 'target/x.war', 'production' echo 'Deployed to http://localhost:8888/production/' } } def deploy(war, id) { sh "cp ${war} /tmp/webapps/${id}.war" } def undeploy(id) { sh "rm /tmp/webapps/${id}.war" } return this; ================================================ FILE: gitcommit.groovy ================================================ // Orig Ref From :: https://github.com/jenkinsci/pipeline-examples/blob/master/pipeline-examples/gitcommit/gitcommit.groovy // These should all be performed at the point where you've // checked out your sources on the slave. A 'git' executable // must be available. // Most typical, if you're not cloning into a sub directory sh('git rev-parse HEAD > GIT_COMMIT') git_commit=readFile('GIT_COMMIT') // short SHA, possibly better for chat notifications, etc. short_commit=git_commit.take(6) //create a GIT_COMMIT file in workspace and read back into a string in Pipeline // If you have your sources checked out in a 'src' subdir sh('cd src && git rev-parse HEAD > GIT_COMMIT') git_commit=readFile('src/GIT_COMMIT') // short SHA, possibly better for chat notifications, etc. short_commit=git_commit.take(6) ================================================ FILE: jenkinsfile-complex-promotion-model ================================================ // Orig Ref From :: https://documentation.cloudbees.com/docs/cookbook/_setting_up_a_basic_build_pipeline_with_jenkins.html // Look for flow.groovy in same path def flow node('master') { git branch: 'master', changelog: false, poll: true, url: 'https://github.com/lavaliere/workflow-plugin-pipeline-demo.git' flow = load 'flow.groovy' flow.devQAStaging() } flow.production() ================================================ FILE: jenkinsfile-conditional-os ================================================ #!groovy // Orig Ref From :: https://github.com/loverde/jenkinsfile-test/blob/master/Jenkinsfile stage name: 'setup' node { if (isUnix()) { echo "unix mode" sh 'pwd' sh "ls -la" } else { echo "windows mode" bat "pwd" bat "dir" } /* wrap([$class: 'Groovy']) { def script = ''' println "\n\nSystem Properties" System.properties.each { k,v -> println "$k = $v" } println "\n\nEnvironment" System.getenv().each { k,v -> println "$k = $v" } ''' } */ // Testing git url: 'https://github.com/loverde/jenkinsfile-test' } stage name: 'build' node { if (isUnix()) { sh './gradlew clean build' } else { bat './gradlew.bat clean build' } } stage name: 'postbuild' node { if (isUnix()) { sh 'ls -la' } else { bat 'dir' } } ================================================ FILE: jenkinsfile-credentials-binding ================================================ // Orig Ref From :: https://cloudbees.zendesk.com/hc/en-us/articles/204897020-Fetch-a-userid-and-password-from-a-Credential-object-in-a-Pipeline-job- node('') { withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: '', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) { sh 'echo uname=$USERNAME pwd=$PASSWORD' } } node('') { withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: '', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) { bat ''' echo %USERNAME% ''' } } node('') { withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: '', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) { println(env.USERNAME) } } ================================================ FILE: jenkinsfile-import-groovy-scripts ================================================ // Orig Ref from :: https://github.com/jenkinsci/pipeline-examples/blob/master/pipeline-examples/load-from-file/pipeline.groovy node { // Load the file 'externalMethod.groovy' from the current directory, into a variable called "externalMethod". def externalMethod = load("externalMethod.groovy") // Call the method we defined in externalMethod. externalMethod.lookAtThis("Steve") // Now load 'externalCall.groovy'. def externalCall = load("externalCall.groovy") // We can just run it with "externalCall(...)" since it has a call method. externalCall("Steve") } ================================================ FILE: jenkinsfile-include-groovy-script ================================================ #!groovy // Orig Ref From :: https://github.com/jenkinsci/pipeline-examples/blob/master/global-library-examples/global-function/Jenkinsfile // Loads the standardBuild function/step from workflowLibs.git/vars/standardBuild.groovy // and invokes it. standardBuild { environment = 'golang:1.5.0' mainScript = ''' go version go build -v hello-world.go ''' postScript = ''' ls -l ./hello-world ''' } ================================================ FILE: jenkinsfile-multiple-os-parallel ================================================ stage "unit test" node { git "git@github.com:michaelneale/oaks-trail-ride.git" sh "echo unit test app" } stage "test on supported OSes" parallel ( windows: { node { sh "echo building on windows now" }}, mac: { node { sh "echo building on mac now" }} ================================================ FILE: jenkinsfile-parallel-jobs ================================================ // Orig Ref From :: https://github.com/jenkinsci/pipeline-examples/blob/master/pipeline-examples/jobs-in-parallel/jobs_in_parallel.groovy // in this array we'll place the jobs that we wish to run def branches = [:] //running the job 4 times concurrently //the dummy parameter is for preventing mutation of the parameter before the execution of the closure. //we have to assign it outside the closure or it will run the job multiple times with the same parameter "4" //and jenkins will unite them into a single run of the job for (int i = 0; i < 4; i++) { branches["branch${i}"] = { //Parameters: //param1 : an example string parameter for the triggered job. //dummy: a parameter used to prevent triggering the job with the same parameters value. this parameter has to accept a different value //each time the job is triggered. build job: 'test_jobs', parameters: [[$class: 'StringParameterValue', name: 'param1', value: 'test_param'], [$class: 'StringParameterValue', name:'dummy', value: "${i}"]] } } parallel branches ================================================ FILE: jenkinsfile-push-to-git-repo ================================================ // Orig Ref From :: https://github.com/jenkinsci/pipeline-examples/blob/master/pipeline-examples/push-git-repo/pushGitRepo.Groovy // This is currently the best way to push a tag (or a branch, etc) from a // Pipeline job. It's not ideal - https://issues.jenkins-ci.org/browse/JENKINS-28335 // is an open JIRA for getting the GitPublisher Jenkins functionality working // with Pipeline. // credentialsId here is the credentials you have set up in Jenkins for pushing // to that repository using username and password. withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'MyID', usernameVariable: 'GIT_USERNAME', passwordVariable: 'GIT_PASSWORD']]) { sh("git tag -a some_tag -m 'Jenkins'") sh('git push https://${GIT_USERNAME}:${GIT_PASSWORD}@ --tags') } // There isn't as trivial a way to override the ssh key if you want to push that // way, but I hope to add that here once I find a reasonable approach. ================================================ FILE: jenkinsfile-set-env-vars ================================================ env.JAVA_HOME = tool 'jdk-1.8.0' // Advice: don't define M2_HOME in general. Maven will autodetect its root fine. def mvnHome = tool 'maven-3.2.1' env.PATH="${env.JAVA_HOME}/bin:${mvnHome}/bin:${env.PATH}" ================================================ FILE: jenkinsfile-stash-unstash ================================================ // First we'll generate a text file in a subdirectory on one node and stash it. stage "first step on first node" // Run on a node with the "first-node" label. node('first-node') { // Make the output directory. sh "mkdir -p output" // Write a text file there. writeFile file: "output/somefile", text: "Hey look, some text." // Stash that directory and file. // Note that the includes could be "output/", "output/*" as below, or even // "output/**/*" - it all works out basically the same. stash name: "first-stash", includes: "output/*" } // Next, we'll make a new directory on a second node, and unstash the original // into that new directory, rather than into the root of the biuld. stage "second step on second node" // Run on a node with the "second-node" label. node('second-node') { // Run the unstash from within that directory! dir("first-stash") { unstash "first-stash" } // Look, no output directory under the root! // pwd() outputs the current directory Pipeline is running in. sh "ls -la ${pwd()}" // And look, output directory is there under first-stash! sh "ls -la ${pwd()}/first-stash" } ================================================ FILE: jenkinsfile-timestamperWrapper ================================================ // Orig Ref from :: https://github.com/jenkinsci/pipeline-examples/blob/master/pipeline-examples/timestamper-wrapper/timestamperWrapper.groovy // This shows a simple build wrapper example, using the Timestamper plugin. node { // This is the current syntax for invoking a build wrapper, naming the class. wrap([$class: 'TimestamperBuildWrapper']) { // Just some echoes to show the timestamps. stage "First echo" echo "Hey, look, I'm echoing with a timestamp!" // A sleep to make sure we actually get a real difference! stage "Sleeping" sleep 30 // And a final echo to show the time when we wrap up. stage "Second echo" echo "Wonder what time it is now?" } } ================================================ FILE: jenkinsfile-types-of-build-cause ================================================ // Orig Ref From :: https://github.com/benwtr/jenkins_experiment/blob/master/Jenkinsfile properties [ [ $class: 'ParametersDefinitionProperty', parameterDefinitions: [ [ $class: 'ChoiceParameterDefinition', choices: ['plan', 'apply'], description: 'When this job is invoked directly, action that TF will perform', name: 'tf_action' ], [ $class: 'GitParameterDefinition', branch: '', branchFilter: '.*', defaultValue: 'master', description: 'Branch to use for plan when this job is invoked directly. This is ignored and always "master" when tf_action is apply', name: 'git_branch', quickFilterEnabled: true, sortMode: 'ASCENDING_SMART', tagFilter: '*', type: 'PT_BRANCH' ] ] ] ] // https://github.com/jenkinsci/pipeline-examples/blob/master/pipeline-examples/get-build-cause/getBuildCause.groovy def causes = currentBuild.rawBuild.getCauses() println causes.dump() println causes causes = '' PRCause = currentBuild.rawBuild.getCause(org.jenkinsci.plugins.github.pullrequest.GitHubPRCause) SCMCause = currentBuild.rawBuild.getCause(hudson.triggers.SCMTrigger$SCMTriggerCause) UserCause = currentBuild.rawBuild.getCause(hudson.model.Cause$UserIdCause) if (PRCause) { println PRCause.properties } else if (SCMCause) { println SCMCause.properties } else if (UserCause) { println UserCause.properties } else { error 'This job cant be triggered however it was just triggered, sorry.' } PRCause = null SCMCause = null UserCause = null ================================================ FILE: slackNotify.groovy ================================================ // Orig Ref From :: https://github.com/jenkinsci/pipeline-examples/blob/master/pipeline-examples/slacknotify/slackNotify.groovy import groovy.json.JsonOutput // Add whichever params you think you'd most want to have // replace the slackURL below with the hook url provided by // slack when you configure the webhook def notifySlack(text, channel) { def slackURL = 'https://hooks.slack.com/services/xxxxxxx/yyyyyyyy/zzzzzzzzzz' def payload = JsonOutput.toJson([text : text, channel : channel, username : "jenkins", icon_emoji: ":jenkins:"]) sh "curl -X POST --data-urlencode \'payload=${payload}\' ${slackURL}" } ================================================ FILE: standardBuild.groovy ================================================ // See https://github.com/jenkinsci/workflow-plugin/tree/master/cps-global-lib#defining-global-functions // The call(body) method in any file in workflowLibs.git/vars is exposed as a // method with the same name as the file. def call(body) { def config = [:] body.resolveStrategy = Closure.DELEGATE_FIRST body.delegate = config body() stage 'checkout' node { checkout scm stage 'main' docker.image(config.environment).inside { sh config.mainScript } stage 'post' sh config.postScript } }