Jenkins Pipeline Choose Specific Branch but take from default(master) branch - jenkins-pipeline

I have a Jenkins Pipeline that I would like to have a user input on to checkout a specific branch of their choosing. i.e. If I create a branch 'dev' and commit it in git,but Jenkins take a default branch(master)
Can any one please help me take a code from 'dev' branch code
Thanks much in advance.
stage('Git Checkout') {
steps {
checkout(
[$class: 'GitSCM',
branches: [[name: '*/dev']],
doGenerateSubmoduleConfigurations: false,
extensions: [],
submoduleCfg: [],
userRemoteConfigs: [[credentialsId:'987654322234245676543',
url:'http://repo.xyz.com/user/devop.git']]]
)
}
}

You can try pipeline step: git
stage('Git Checkout') {
steps {
git(branch: 'dev',
credentialsId: '987654322234245676543',
url: "http://repo.xyz.com/user/devop.git")
}
}

Related

pipline script that i can’t seem to understand

i have a declarative pipeline that was causing me some problems lately. i put my hand on the block of script that was the source of the problem but since i’m new to jenkins i can’t figure out what it does exactly and here is the block :
checkout changelog: true, poll: true, scm: [
$class: 'GitSCM',
branches: [[name: "origin/${env.gitlabSourceBranch}"]],
doGenerateSubmoduleConfigurations: false,
extensions: [[$class: 'PreBuildMerge', options: [fastForwardMode: 'NO_FF', mergeRemote: 'origin', mergeStrategy: 'DEFAULT', mergeTarget: "${env.gitlabTargetBranch}"]]],
submoduleCfg: [],
userRemoteConfigs: [[credentialsId: "${env.GIT_REPO_CREDENTIAL_ID}",name: 'origin', url: pipelineParams.scmUrl ]]
]
can someone please help me figure out what this does exactly when i run it through a jenkins build ?
P.S : this block is inside of a try/catch

How to refer to the parameters in groovy pipeline script?

I merged this as vars/gitCheckout.goovy add this as library into the jenkins
def call(String branch = '*/master') {
checkout([$class: 'GitSCM',
branches: [[name: ${branch}]],
doGenerateSubmoduleConfigurations: false,
extensions: [[$class: 'SubmoduleOption',
disableSubmodules: false,
parentCredentials: false,
recursiveSubmodules: true,
reference: '',
trackingSubmodules: false]],
submoduleCfg: [],
userRemoteConfigs: [[url: 'https://my-server.com/some/project.git']]])
}
Calling this method as below from jenkins Pipeline Script:
#Library('jenkins-library#master') _
pipeline {
agent { label 'my-server' }
stages {
stage('Git Checkout') {
steps {
gitCheckout()
}
}
}
}
This fails with error java.lang.NoSuchMethodError: No such DSL method '$' found among steps [ArtifactoryGradleBuild, MavenDescriptorStep, ....
I tried $branch, params.branch, but it didn't work, the code otherwise works if I don't use parameter and hardcode the branch name. Also, whenever I make any update to this .groovy script, should I test it by merging and running it as jenkins job? is there any other way to test before merging the groovy script ?
Replace ${branch} in the 3rd line with just branch. You use $ with a variable name when you e.g. interpolate variables inside Groovy strings:
def value = "current branch is: ${branch}" // produces: current branch is */master
If you forgot to use $ in string interpolation, nothing would happen:
def value = "current branch is: branch" // produces: current branch is branch

Jenkins Pipeline - Parallel steps skip latest Git commits and Ruby's Bundler commands pause unexpectedly

I am writing my first declarative pipeline and I would like to run the Git Checkout and Bundler stage in parallel. When the steps from these stages are executed in parallel, I experience odd behaviors. For example:
I want to check out the latest copy of a PR to test. In the parallel step, the check out will fail to get the latest commit and will fetch an older commit as the HEAD. I have verified that the BitBucket server has newer commits than the one checked out.
Figured this out: In Bitbucket server, you need to manually access the PR page and refresh the "commit cache". This way the latest commits are served to Jenkins.
Source: https://community.atlassian.com/t5/Bitbucket-questions/Change-pull-request-refs-after-Commit-instead-of-after-Approval/qaq-p/194702
I want to run Ruby's Bundler gem (bundle install & update) in 4 different repositories at the same time. When the parallel step executes, it would unexpectedly pause/hang on bundle install in the cr_dbvals repos and not print anything to the console. Have to abort the build at this point.
Agents OS: Windows 10 x64
Running these steps sequentially yields the expected results and everything works fine. Not sure what I am missing in my script here:
pipeline {
agent {
node {
label "${env.executor_label}"
}
}
stages {
stage('Set Build Name') {
steps {
script {
currentBuild.displayName = "#${env.BUILD_NUMBER} - ${env.app_node} - ${env.browser}#${env.NODE_NAME}"
}
}
} // stage('Set Build Name')
stage('Git Checkout') {
steps {
parallel(
"Git Cucumber-Watir": {
dir('cucumber-watir') {
git(url: 'http://git-repo-url/cucumber-watir.git', branch: 'master', changelog: true)
bat(script: 'git config --add remote.origin.fetch +refs/pull-requests/*/from:refs/remotes/origin/pr/*')
bat(script: 'git fetch origin -p')
bat(script: "git checkout ${env.cucumber_watir_branch}")
}
},
"Git CrModels": {
dir('cr_models') {
git(url: 'http://git-repo-url/cr_models.git', branch: 'master', changelog: true)
bat(script: 'git config --add remote.origin.fetch +refs/pull-requests/*/from:refs/remotes/origin/pr/*')
bat(script: 'git fetch origin -p')
bat(script: "git checkout ${env.cr_models_branch}")
}
},
"Git CaModels": {
dir('ca_models') {
git(url: 'http://git-repo-url/ca_models.git', branch: 'master', changelog: true)
bat(script: 'git config --add remote.origin.fetch +refs/pull-requests/*/from:refs/remotes/origin/pr/*')
bat(script: 'git fetch origin -p')
bat(script: "git checkout ${env.ca_models_branch}")
}
},
"Git CrDbVal": {
dir('cr_dbvals') {
git(url: 'http://git-repo-url/cr_dbvals.git', branch: 'master', changelog: true)
bat(script: 'git config --add remote.origin.fetch +refs/pull-requests/*/from:refs/remotes/origin/pr/*')
bat(script: 'git fetch origin -p')
bat(script: "git checkout ${env.cr_dbvals_branch}")
}
}
) // parallel
} // steps
} // stage('Git Checkout')
stage('Bundler') {
steps {
parallel(
"Bundle Cucumber-Watir": {
dir('cucumber-watir') {
bat(script: "bundle install")
bat(script: "bundle update")
}
},
"Bundle CrModels": {
dir('cr_models') {
bat(script: "bundle install")
bat(script: "bundle update")
}
},
"Bundle CaModels": {
dir('ca_models') {
bat(script: "bundle install")
bat(script: "bundle update")
}
},
"Bundle CrDbVal": {
dir('cr_dbvals') {
bat(script: "bundle install")
bat(script: "bundle update")
}
}
) // parallel
} // steps
} // stage('Bundler')
stage('Execute Test(s)') {
steps {
dir(path: 'cucumber-watir') {
bat 'set NLS_LANG=AMERICAN_AMERICA.WE8ISO8859P1'
bat(script: 'cucumber -t %tags% -f json -o cucumber.json -f pretty --expand')
}
} // steps
} // stage('Execute Test(s)')
} // stages
post {
always {
dir(path: 'cucumber-watir') {
cucumber 'cucumber.json' // Build Cucumber Report
}
deleteDir() // Cleanup
} // always
} // post
} // pipeline

Jenkinsfile conditions in Stage phase

should it possible to define several conditions in a Stage phase of Jenkins file??
Let me to explain my problem: I want to publishHtml in my Jenkins pipeline only if a condition is valid:
stage(Documentation)
{
agent any
steps
{
sh"./documents.sh " //This generate the documentation of several modules
if(firstModule) { //Is it possible to publishHTML only if documentation of this module was generated???
publishHTML (target: [
allowMissing: false,
alwaysLinkToLastBuild: false,
keepAll: true,
reportDir: "${env.WORKSPACE}/firstModule//html",
reportFiles: 'index.html',
reportName: "Fist Module Documentation"
])
}
if(secondModule) { //Is it possible to publishHTML only if documentation of this module was generated???
publishHTML (target: [
allowMissing: false,
alwaysLinkToLastBuild: false,
keepAll: true,
reportDir: "${env.WORKSPACE}/secondModule/html",
reportFiles: 'index.html',
reportName: "Second Modul Documentation"
])
}
}
I don't know if firstModule was built or not... this is what I would like to know.
I don't want to create different stages, but just one "Documentation" visible in the jenkins view.
Thank for your suggestion.
Prisco
it sounds like you want to publish documentation for firstModule only if "${env.WORKSPACE}/firstModule/html/index.html exists.
instead of:
if(firstModule) {
try:
script {
if (fileExists("${env.WORKSPACE}/firstModule/html/index.html")) {
# publishHTML and whatnot
}
}

Grunt Shell + Heroku Push = No stdout

Using Grunt to build, add, commit and push my code up to Heroku.
Build, add and commit are working great.
When I specify to "git push heroku master" in grunt shell I get no stdout while the process runs.
Here is the code in Grunt.js:
'git-push': {
command: 'git push heroku master',
options: {
failOnError: true,
stdout: true,
execOptions: { cwd: '../deploy'}
}
}
But I am only seeing the following when the process runs:
$ grunt push
Running "shell:git-push" (shell) task
Done, without errors.
I would like to see the output of the push while the push is in process.
Anyway to do this?
Update: Full grunt shell script
shell: {
'git-add': {
command: 'git --no-pager add .',
options: {
stdout: true,
execOptions: { cwd: '../deploy'}
}
},
'git-commit': {
command: 'git --no-pager commit -m "update"',
options: {
stdout: true,
execOptions: { cwd: '../deploy'}
}
},
'git-push': {
command: 'git --no-pager push heroku master',
options: {
failOnError: true,
stdout: true,
execOptions: { cwd: '../deploy'}
}
}
}
Final Grunt Shell (working):
shell: {
'git-add': {
command: 'git --no-pager add .',
options: {
stdout: true,
stderr: true,
execOptions: { cwd: '../deploy'}
}
},
'git-commit': {
command: 'git --no-pager commit -m "update"',
options: {
stdout: true,
stderr: true,
execOptions: { cwd: '../deploy'}
}
},
'git-push': {
command: 'git --no-pager push heroku master',
options: {
failOnError: true,
stdout: true,
stderr: true,
execOptions: { cwd: '../deploy'}
}
}
}
See:
How to make git diff write to stdout?
Adding --no-pager as an option, gives output.
git --no-pager <subcommand> <options>
Also, certain git commands write to stderr,as discussed here:
http://git.661346.n2.nabble.com/git-push-output-goes-into-stderr-td6758028.html
By including the flag and capturing stderr in the grunt task I was able to get output for the last part of the heroku push process (but not the part where the upload is tracked):
Fetching repository, done.
-----> Node.js app detected
PRO TIP: Specify a node version in package.json
See https://devcenter.heroku.com/articles/nodejs-support

Resources