Job result is the Post Script result - jenkins

I'm building a pipeline and I have two post-build scripts in case of success and unsuccess.
pipeline {
agent any
stages {
stage('Build') {
steps {
script {
echo 'Building...'
}
}
}
...
}
post {
unsuccessful {
script {
build job: '../declinePullRequests'
}
}
}
success {
script {
build job: '../createPR_mergePR'
}
}
}
}
}
However, I want my job to return immediatly after it finishes, and not to get blocked by the post-build step. Basically, if the post-script fails, the main job console shows:
Error when executing success post condition:
hudson.AbortException: createPR_mergePR #40 completed with status FAILURE (propagate: false to ignore)
at org.jenkinsci.plugins.workflow.support.steps.build.BuildTriggerListener.onCompleted(BuildTriggerListener.java:52)
at hudson.model.listeners.RunListener.fireCompleted(RunListener.java:211)
at hudson.model.Run.execute(Run.java:1861)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:429)
And the main job fails due to failure in post-script job, though it was successful before it. I've researched in the docs and cannot find a solution for it.
How can my main job return immediately after being finished, independently from the post-script job result?
I don't only want to keep the original job state but also not to wait for the child job to get the main job finished.

Try setting the properties propagate and wait explicitly to false.
build job: '../declinePullRequests', propagate: false, wait: false

Hi looks like you what to spawn processes which run even when the original build is finished. If its possible to pack your scripts into shell/batch, take a look at this two sites:
https://wiki.jenkins.io/display/JENKINS/Spawning+processes+from+build
https://support.cloudbees.com/hc/en-us/articles/218517228-How-to-Ignore-Failures-in-a-Shell-Step-

Related

Prevent Jenkins job from building from another jenkins file

We have 2 jenkins job AA and BB.
Is there a way to allow BB only to be trigger from AA after it completes?
Basically, you can use build triggers to do this. More about build triggers can be found here. There are two ways to add build triggers. Following is how you can add triggers using the UI. By going to Configure Job you can add triggers. Please refer to the following image.
In a declarative pipeline, you can add triggers as shown below.
pipeline {
agent any
triggers { upstream(upstreamProjects: 'AA', threshold: hudson.model.Result.SUCCESS) }
stages {
stage('Hello') {
steps {
echo 'Hello World BB'
}
}
}
}
Here you can specify the threshold on when to trigger the build based on the status of the upstream build. There are 4 different thresholds.
hudson.model.Result.ABORTED: The upstream build was manually aborted.
hudson.model.Result.FAILURE: The upstream build had a fatal error.
hudson.model.Result.SUCCESS: The upstream build had no errors.
hudson.model.Result.UNSTABLE: The upstream build had an unstable result.
Update 02
If you want to restrict all other jobs/users from triggering this job you will have to restructure your Job. You can wrap your stages with a parent Stage and conditionally check who triggered the Job. But note that the Job will anyway trigger but the stages will be skipped. Please refer the following pipeline.
pipeline {
agent any
triggers { upstream(upstreamProjects: 'AA', threshold: hudson.model.Result.SUCCESS) }
stages{
stage('Parent') {
// We will restrict triggering this Job for everyone other than Job AA
when { expression {
print("Checking if the Trigger is allowed to execute this job")
print('AA' in currentBuild.buildCauses.upstreamProject)
}
}
stages {
stage('Hello') {
steps {
echo 'Hello World BB'
}
}
}
}
}
}

Trigger Sonar Jenkins job from another Jenkins job

I want to create a process in Jenkins when one job is building it should internally call another job that is generating a SONAR report for the same code pull request.
When I am trying to call API to trigger Jenkins job automatically.
https://jenkins.com/job/DPNew/job/xyz/buildWithParameters?token=DW&FROM_HASH=195c8df91791768f3098ce260eb2dd8728&REPO_NAME=_python&PROJECT_KEY=%7Eabc&EMAIL=abc#gmail.com&FROM_BRANCH_NAME=feature%2FDO-451&TO_BRANCH_NAME=Port-2.7&PR_ID=622"
I am getting below error in response.
content: "<html><head><body style='background-color:white;
color:white;'>\n\n\nAuthentication required\n<!--\nYou are authenticated as: anonymous\nGroups that you are in:\n \nPermission you need to have (but didn't):
hudson.model.Hudson.Read\n ... which is implied by: hudson.security.Permission.GenericRead\n ... which is implied by:
hudson.model.Hudson.Administer\n-->\n\n</body></html>
I have already created Jenkins API token in 'user -> configure'
Edit 1:
The first Jenkin job is triggered by a pull request from Bitbucket, and the UI in bitbucket shows if the build is successful and if the build is a success it shows a sonar report.
What should I do to resolve this issue?
Instead of API call, use job, this will also make it so you can use paramers from your sonar report job and display them here/use them.
example:
pipeline {
agent any
stages {
stage('stage_name') {
steps {
build job: 'JOB_NAME'
}
}
}
}
Or with parameters:
pipeline {
agent any
stages {
stage('stage_name') {
steps {
build job: 'JOB_NAME_HERE', propagate: true, parameters:
[
[
$class: 'StringParameterValue',
name: 'STRING_NAME_HERE',
value: "STRING_VALUE_HERE"
]
]
}
}
}
}
propagate: true means that the original job will fail if JOB_NAME_HERE fails.

Skip a Jenkins build stage, but keep it running in the background

Is it possible to skip a Jenkins build step without reporting its status back?
// Build Stage
stage('build') {
}
// Test Stage
stage('test') {
}
// Run at last
stage('Last stage') {
// I want to mark entire build as succeed regardless of following code
//and do not want it to wait for the following code and pipeline to get completed.
sh """
"""
parallel 'name': {
build job: "jobname1", propagate: true, wait: false
}, 'pipeline2': {
build job: "jobname2", propagate: true, wait: false
}
}
As you can see in the above code block, I want to execute the last stage code and pipelines, but before it gets completed I want to mark the main build as 'Success' status regardless of this code block.
This last stage currently takes more than 2 hrs, and I want it to get skipped for the notifying status but actually exected in the background.
Is this achievable?
I think the issue is that you set propagate to true, which means the job has to wait to determine status of the build. If you set propagate to false and wait to false then the jobs simply run and your pipeline completes successfully. Also given that I don't think there is much benefit to executing the builds in parallel.

Run a build after creating it with DSL Job Plugin

I have successfully programatically created a job with DSL Job Plugin
I trigger the "job creator" job from gitlab, hitting a post with:
https://37.35.xxx.xxx/jenkins/project/job-creator
So, it create the job, but it is not triggering it... Any idea how to do it ?
After a while, I found out you can use upstream trigger:
pipelineJob("myJob") {
parameters {
stringParam('param1', 'value1') // this will define params for the project build
}
triggers {
gitlabPush {
buildOnMergeRequestEvents()
buildOnPushEvents()
commentTrigger('Jenkins please retry a build')
upstream("${JOB_NAME}", 'SUCCESS') // Trigger job after this job ends
}
}

How can i use 'parallel' option in jenkins pipeline in the 'post' section?

I looked at many pipeline examples and how to write the post build section in a pipeline script. But never got my answer i was looking for.
I have 4 jobs - say Job A,B,C and D. I want job A to run first, and if successful it should trigger Job B,C,D in parallel. If Job A fails, it should trigger only Job B. Something like below:
pipeline {
agent any
stages {
stage('Build_1') {
steps {
sh '''
Build Job A
'''
}
}
post {
failure {
sh '''
Build Job B
'''
}
success {
sh '''
Build Job B,C,D in parallel
'''
}
}
}
I tried using 'parallel' option in post section but it gave me errors. Is there a way to build Job B,C,D in parallel, in the post 'success' section?
Thanks in advance!
The parallel keyword actually can work inside a post condition as long as it is encapsulated inside a script block, as the script blocks is just a fallback to the scripted pipeline which will allow you to run parallel execution step wherever you want.
The following should work fine:
pipeline {
agent any
stages {
stage('Build_1') {
steps {
// Build Job A
}
}
}
post {
failure {
// run job B
build job: 'Job-B'
}
success {
script {
// run jobs B, C, D in parallel
def jobs = ['Job-B', 'Job-C', 'Job-D']
parallel jobs.collectEntries { job ->
["Building ${job}" : {
build job: job
}]
}
}
}
}
}
This is just an example and specific parameters or configuration (for the build keyword) can be added to each job execution according to your needs.
The error message is quiet clear about this:
Invalid step "parallel" used - not allowed in this context - The
parallel step can only be used as the only top-level step in a stages
step
The more restrictive declarative syntax does not allow the usage of parallel in thw post section at the moment.
If you don't want to switch to the scripted syntax, another option that should work: Build the jobs B,C,D in parallel in a second stage and move the the failure condition in the post section of your first stage. As a result job B,C,D will run if A is successful. If A is not successful only job B will run.
pipeline {
agent any
stages {
stage('one') {
steps {
// run job A
}
post {
failure {
// run job B
}
}
}
stage('two') {
steps {
parallel(
// run job B, C, D
)
}
}
}
}

Resources