So I have a jenkins job that checkout a svn repo like this remote: "svn://xyz-repo/svn/xyzclientjs/$BRANCH_NAME"]],
I pass this $BRANCH_NAME through a Jenkinsfile that is present in this svn repo.
Now Inside Jenkinsfile I am doing this -
node 'xyz-169' {
checkout scm
def BRANCH_NAME = sh "svn info | grep -Po 'Relative URL: \\^/\\K.*'"
def BRANCH_REV = sh "svn info --show-item revision"
stage('Build A') {
build job: 'xyzclientjs-webui-test', propagate: true, parameters:
[
[$class: 'StringParameterValue', name: 'BRANCH_NAME', value: $env.BRANCH_NAME],
[$class: 'StringParameterValue', name: 'BRANCH_REV', value: $env.BRANCH_REV],
]
But when I run the job on jenkins I get following error
Error while checking out xyzclientjs branch from SVN
10:26:05 [Pipeline] error
10:26:05 [Pipeline] }
10:26:05 [Pipeline] // stage
10:26:05 [Pipeline] }
10:26:05 [Pipeline] // node
10:26:05 [Pipeline] End of Pipeline
10:26:05 java.lang.ClassCastException: org.jenkinsci.plugins.workflow.steps.ErrorStep.message expects class java.lang.String but received class groovy.lang.MissingPropertyException
Is there any way to do this. Please help any suggestions would be highly appriciated.
You should have a look here for an example to correctly fetch the output of a sh step:
How do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?
For example (not tested due to lack of SVN):
def BRANCH_NAME = sh (
script: "svn info | grep -Po 'Relative URL: \\^/\\K.*'",
returnStdout: true
).trim()
I have one pipeline and one other job. i want to pass parameter.
This is my groovy script which is inside pipeline job.
pipeline {
agent any
stages {
stage('release') {
steps {
echo 'This is release!'
echo branch
build job: projectname , parameters: [[$class: 'StringParameterValue', name: 'branch', value: branch]]
}
}
So this branch i want to pass into build job. echo branch also printing perfectly.
And this is how i tried to get my branch name from release job
This trigger an error.
org.tmatesoft.svn.core.SVNException: svn: E160005: Target path '/${branch}' does not exist
It does not resolve to the branch name which i want
This should work:
build job: projectname , parameters: [string(name: 'branch', value: "${branch}")]
I have a separate build pipeline that uses jenkinsfile to build the code.
I trigger it from a deploy pipeline and want to get build results.
The reason for this is that devs can define build steps but deploy is out of there control.
Here's a sample code in jenkins job builder:
- job:
name: Build and Deploy
project-type: pipeline
dsl: |
node {
stage('Build') {
# that job does stash inside a jenkinsfile
build job: "Build"
sh 'cp -rv "../Build/dist/" ./' # this is a workaround
stash includes: 'dist/*.zip', name: 'archive'
}
stage('Deploy') {
unstash 'archive'
sh "..."
}
}
So how can I unstash code stash-ed in a sub-job?
P.S.: there's also a workaround with artefacts:
In a sub-job:
archiveArtifacts artifacts: '*.zip', fingerprint: true
main DSL:
dsl: |
node {
def build_job_number = 0
def JENKINS = "http://127.0.0.1:8080"
stage('Build') {
def build_job = build job: "Build"
build_job_number = build_job.getNumber()
}
stage('Deploy') {
sh "wget -c --http-user=${USER} --http-password=${TOKEN} --auth-no-challenge ${JENKINS}/job/Build/${build_job_number}/artifact/name.zip"
sh "..."
}
}
The issue here is that API token is required.
If you go with archiveArtifacts you can use copyArtifacts to complement it.
As far as I know stash/unstash only work within the same job, so your other option would be to tick the Preserve stashes from completed builds in the pipeline's configuration so you can re-use them.
We have a project on GitHub which has two Jenkins Multibranch Pipeline jobs - one builds the project and the other runs tests. The only difference between these two pipelines is that they have different JenkinsFiles.
I have two problems that I suspect are related to one another:
In the GitHub status check section I only see one check with the following title:
continuous-integration/jenkins/pr-merge — This commit looks good,
which directs me to the test Jenkins pipeline. This means that our build pipeline is not being picked up by GitHub even though it is visible on Jenkins. I suspect this is because both the checks have the same name (i.e. continuous-integration/jenkins/pr-merge).
I have not been able to figure out how to rename the status check message for each Jenkins job (i.e. test and build). I've been through this similar question, but its solution wasn't applicable to us as Build Triggers aren't available in Multibranch Pipelines
If anyone knows how to change this message on a per-job basis for Jenkins Multibranch Pipelines that'd be super helpful. Thanks!
Edit (just some more info):
We've setup GitHub/Jenkins webhooks on the repository and builds do get started for both our build and test jobs, it's just that the status check/message doesn't get displayed on GitHub for both (only for test it seems).
Here is our JenkinsFile for for the build job:
#!/usr/bin/env groovy
properties([[$class: 'BuildConfigProjectProperty', name: '', namespace: '', resourceVersion: '', uid: ''], buildDiscarder(logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '5')), [$class: 'ScannerJobProperty', doNotScan: false]])
node {
stage('Initialize') {
echo 'Initializing...'
def node = tool name: 'node-lts', type: 'jenkins.plugins.nodejs.tools.NodeJSInstallation'
env.PATH = "${node}/bin:${env.PATH}"
}
stage('Checkout') {
echo 'Getting out source code...'
checkout scm
}
stage('Install Dependencies') {
echo 'Retrieving tooling versions...'
sh 'node --version'
sh 'npm --version'
sh 'yarn --version'
echo 'Installing node dependencies...'
sh 'yarn install'
}
stage('Build') {
echo 'Running build...'
sh 'npm run build'
}
stage('Build Image and Deploy') {
echo 'Building and deploying image across pods...'
echo "This is the build number: ${env.BUILD_NUMBER}"
// sh './build-openshift.sh'
}
stage('Upload to s3') {
if(env.BRANCH_NAME == "master"){
withAWS(region:'eu-west-1',credentials:'****') {
def identity=awsIdentity();
s3Upload(bucket:"****", workingDir:'build', includePathPattern:'**/*');
cfInvalidate(distribution:'EBAX8TMG6XHCK', paths:['/*']);
}
};
if(env.BRANCH_NAME == "PRODUCTION"){
withAWS(region:'eu-west-1',credentials:'****') {
def identity=awsIdentity();
s3Upload(bucket:"****", workingDir:'build', includePathPattern:'**/*');
cfInvalidate(distribution:'E6JRLLPORMHNH', paths:['/*']);
}
};
}
}
Try to use GitHubCommitStatusSetter (see this answer for declarative pipeline syntax). You're using a scripted pipeline syntax, so in your case it will be something like this (note: this is just prototype, and it definitely must be changed to match your project specific):
#!/usr/bin/env groovy
properties([[$class: 'BuildConfigProjectProperty', name: '', namespace: '', resourceVersion: '', uid: ''], buildDiscarder(logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '5')), [$class: 'ScannerJobProperty', doNotScan: false]])
node {
// ...
stage('Upload to s3') {
try {
setBuildStatus(context, "In progress...", "PENDING");
if(env.BRANCH_NAME == "master"){
withAWS(region:'eu-west-1',credentials:'****') {
def identity=awsIdentity();
s3Upload(bucket:"****", workingDir:'build', includePathPattern:'**/*');
cfInvalidate(distribution:'EBAX8TMG6XHCK', paths:['/*']);
}
};
// ...
} catch (Exception e) {
setBuildStatus(context, "Failure", "FAILURE");
}
setBuildStatus(context, "Success", "SUCCESS");
}
}
void setBuildStatus(context, message, state) {
step([
$class: "GitHubCommitStatusSetter",
contextSource: [$class: "ManuallyEnteredCommitContextSource", context: context],
reposSource: [$class: "ManuallyEnteredRepositorySource", url: "https://github.com/my-org/my-repo"],
errorHandlers: [[$class: "ChangingBuildStatusErrorHandler", result: "UNSTABLE"]],
statusResultSource: [ $class: "ConditionalStatusResultSource", results: [[$class: "AnyBuildResult", message: message, state: state]] ]
]);
}
Please check this and this links for more details.
You can use the Github Custom Notification Context SCM Behaviour plugin https://plugins.jenkins.io/github-scm-trait-notification-context/
After installing go to the job configuration. Under "Branch sources" -> "GitHub" -> "Behaviors" click "Add" and select "Custom Github Notification Context" from the dropdown menu. Then you can type your custom context name into the "Label" field.
This answer is pretty much like #biruk1230's answer. But if you don't want to downgrade your github plugin to work around the bug, then you could call the API directly.
void setBuildStatus(String message, String state)
{
env.COMMIT_JOB_NAME = "continuous-integration/jenkins/pr-merge/sanity-test"
withCredentials([string(credentialsId: 'github-token', variable: 'TOKEN')])
{
// 'set -x' for debugging. Don't worry the access token won't be actually logged
// Also, the sh command actually executed is not properly logged, it will be further escaped when written to the log
sh """
set -x
curl \"https://api.github.com/repos/thanhlelgg/brain-and-brawn/statuses/$GIT_COMMIT?access_token=$TOKEN\" \
-H \"Content-Type: application/json\" \
-X POST \
-d \"{\\\"description\\\": \\\"$message\\\", \\\"state\\\": \\\"$state\\\", \
\\\"context\\\": \\\"${env.COMMIT_JOB_NAME}\\\", \\\"target_url\\\": \\\"$BUILD_URL\\\"}\"
"""
}
}
The problem with both methods is that continuous-integration/jenkins/pr-merge will be displayed no matter what.
This will be helpful with #biruk1230's answer.
You can remove Jenkins' status check which named continuous-integration/jenkins/something and add custom status check with GitHubCommitStatusSetter. It could be similar effects with renaming context of status check.
Install Disable GitHub Multibranch Status plugin on Jenkins.
This can be applied by setting behavior option of Multibranch Pipeline Job on Jenkins.
Thanks for your question and other answers!
Example:
---using stage------------------------------------------------------------------------
stage 'myjob'
node('mynode'){
echo "i am in stage"
}
--using build job------------------------------------------------------------------------
build job: 'myjob',
parameters: [
[$class: 'NodeParameterValue',
name: 'NODE_NAME',
labels: 'mynode',
nodeEligibility: [$class: 'AllNodeEligibility']],
Stage describes a stage of this Pipeline. It is used in the visualization in the Stage View in a job overview page (Jenkins UI). It is basically just a name.
build is a Pipeline Step which triggers a new build for a given job.
For example build job: 'myjob', parameters: [ [$class: 'NodeParameterValue',.. myjob - name of a downstream job to build, parameters - some parameters for this build.