Run a build after creating it with DSL Job Plugin - jenkins

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
}
}

Related

How to get parent jenkins job's name and build number from child job

I have a Build Flow jenkins parent job with a DSL script that starts a Build Flow child job, also with a DSL script. Is there a way (groovy API) to get the parent job's name and build number in the child job?
Here is the Groovy script to get your Upstream Job details.
pipeline {
agent any
stages {
stage('Build') {
steps {
script {
def cause = currentBuild.getBuildCauses('org.jenkinsci.plugins.workflow.support.steps.build.BuildUpstreamCause')
if(cause.size() > 0) { // This is triggred by a upstream Job
def parentJobName = cause[0].upstreamProject
def parentBuildNumber = cause[0].upstreamBuild
echo "Parent JOb: $parentJobName"
echo "Parent Build Number: $parentBuildNumber"
}
}
}
}
}
}
Update
You can get all the causes without passing the Class.
def cause = currentBuild.getBuildCauses()

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.

Job result is the Post Script result

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-

Is there a way to insert a manual approval for Build pipeline 1.5.8 version in jenkins 2

I am using jenkins 2.89.2 version.
For deployment into production system it's often useful to require manual approval; is there a way to insert a manual button to press inside a pipeline?
I tried using Build other Project(manual Step) in post build action but still i don't see any approval button or manual intervention at prod build in build pipeline.. And as i can see that In Build pipeline ---> Manually trigger downstream projects is no more avail in Build pipeline version 1.5.8.
I want to use build pipeline for my project.
Can anyone help on this how to do? Thanks in advance.
That's how I'm doing using Slack integration.
slackSend (channel: "#slack-channel", color: '#4286f4', message: "Deploy Approval: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' (${env.JOB_DISPLAY_URL})")
script {
try {
timeout(time:30, unit:'MINUTES') {
env.APPROVE_PROD = input message: 'Deploy to Production', ok: 'Continue',
parameters: [choice(name: 'APPROVE_PROD', choices: 'YES\nNO', description: 'Deploy from STAGING to PRODUCTION?')]
if (env.APPROVE_PROD == 'YES'){
env.DPROD = true
} else {
env.DPROD = false
}
}
} catch (error) {
env.DPROD = true
echo 'Timeout has been reached! Deploy to PRODUCTION automatically activated'
}
}
I have not done this yet but one way to add approvals could be by using "Input Step"
It is documented here:
https://jenkins.io/doc/pipeline/steps/pipeline-input-step/

Resources