Trigger builds remotely (e.g., from scripts) syntax in Jenkinsfile - jenkins

I am using this option in my freestyle jobs but now my team is moving to make a standard format so I have to write all my freestyle jobs in Pipeline script and I google a lot but didn't get how could I write this option in the Pipeline script.

You can trigger remote Jenkins jobs using triggerRemoteJob pipeline step.
Documentation: https://jenkins.io/doc/pipeline/steps/Parameterized-Remote-Trigger/
And here is a short example that illustrates how to use this step with authentication. I used Jenkins User Token for authentication - the token and user name was stored in the Jenkins credentials with id xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (obfuscated id ofc). The remote job in the below example is triggered with a single parameter foo == qwe123, and it is configured to wait until the remote job gets completed, and if it fails, the job that triggered the remote job fails as well.
pipeline {
agent any
stages {
stage("Execute remote job") {
steps {
script {
def jobUrl = "https://remote-jenkins-host/job/remote-job-to-trigger/"
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', usernameVariable: 'USERNAME', passwordVariable: 'TOKEN']]) {
def handle = triggerRemoteJob job: jobUrl,
blockBuildUntilComplete: true,
shouldNotFailBuild: true,
parameters: "foo=qwe123",
auth: TokenAuth(apiToken: env.TOKEN, userName: env.USERNAME)
echo "Remote tests status: ${handle.buildStatus.toString()}"
}
}
}
}
}
}
Hope it helps.

Related

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.

How to pass down variables to credential parameters in JenkinsFiles?

I'm trying to write a JenkinsFile that automatically will reach to a git repo via ssh and perform some actions but I want to make the repo and ssh key use variables with the ssh id stored in Jenkins but I seem to be missing the Jenkins documentation for how to pass down variables to Jenkins Files as I'm not able to pass values down into the credentials key. The variables being passed down to the sh commands resolve perfectly fine though...
Example Pipeline Below:
pipeline {
parameters {
string(name: 'SSH_priv', defaultValue: 'd4f19e34-7828-4215-8304-a2d1f87a2fba', description: 'SSH Credential with the private key added to Jenkins and the public key to the username stored in Git Server, this id can be found in the credential section of Jenkins post its creation.')
string(name: 'REPO', defaultValue: 'git#--------------------')
}
stages {
stage ('Output Variables'){
// checks I can get these variables
steps{
sh("echo ${params.SSH_priv}")
sh("echo ${params.REPO}")
}
}
stage('Do Something') {
steps {
// this below commented line, does not work.
// sshagent (credentials: ['${params.SSH_priv}']){
// this line does work
sshagent (credentials: ['d4f19e34-7828-4215-8304-a2d1f87a2fba']){
sh("git clone --mirror ${params.REPO} temp")
dir("temp"){
// start doing fancy stuff ...
....
....
}
}
}
}
The aim is a Pipeline that my fellow developers could call and will work with their own repos and own ssh id's that I'm not using. When I try to run this with the SSH_priv parameter passing down the value I get the below failure in Jenkins.
The JenkinsFile works perfectly fine with the credential id hard-coded- as shown below:
So after testing different things a friend solved this in sub 5 minutes. Quotation mark types matter in Groovy Script
Changing
sshagent (credentials: ['${params.SSH_lower}']){
To
sshagent (credentials: ["${params.SSH_lower}"]){
Solved the issue.
Better to use environment step in pipeline.
pipeline {
agent any
environment {
AN_ACCESS_KEY = credentials('an_access_key_id')
}
stages {
stage('Example') {
steps {
sh 'printenv'
}
}
}
}
And credentials should exist in jenkins with id an_access_key_id
Take a look at official documentation here

Webhook| Gitlab | jenkins pipeline |Declarative syntax

I'm trying to integrate Webhook with gitlab and jenkins. I have done it via upstream downstream jobs using the URL.
While trying to rece=reate the same via declarative pipeline, I'm in a stanstill
pipeline {
agent any
stages {
stage('fetchcodeFromGit') {
steps {
timeout(time: 30) {
git(url: 'http:<<>>/JenkinsPipeline.git', branch: 'master', credentialsId: 'QualityAssurance', poll: true)
}
}
}
Can anyone help with documents or any sample snippets?
If you choose pipeline script instead declarative pipeline, this post could be help you :
https://jrichardsz.github.io/devops/devops-with-git-and-jenkins-using-webhooks
Steps:
Configure required plugins in jenkins.
Jenkins user and password.
Create a jenkins job which will be triggered by your git provider. This job publish an http url ready to use. We will call webhook_url to this url.
Configure webhook_url in webhook section of your git provider of some repository.
Test this flow, pushing some change to your git repository or simulating it using comandline.
You can use this snippet:
pipeline {
options {
gitLabConnection('your-gitlab-conn')
}
triggers {
gitlab(
triggerOnPush: false,
triggerOnMergeRequest: true, triggerOpenMergeRequestOnPush: "both",
triggerOnNoteRequest: true,
noteRegex: "Jenkins please retry a build",
skipWorkInProgressMergeRequest: false,
ciSkip: false,
setBuildDescription: true,
addNoteOnMergeRequest: true,
addCiMessage: true,
addVoteOnMergeRequest: true,
acceptMergeRequestOnSuccess: false,
branchFilterType: "All",
secretToken: "NOTVERYSECRET")
}
stages {
...
more details here: https://github.com/jenkinsci/gitlab-plugin

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 trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

How can I trigger build of another job from inside the Jenkinsfile?
I assume that this job is another repository under the same github organization, one that already has its own Jenkins file.
I also want to do this only if the branch name is master, as it doesn't make sense to trigger downstream builds of any local branches.
Update:
stage 'test-downstream'
node {
def job = build job: 'some-downtream-job-name'
}
Still, when executed I get an error
No parameterized job named some-downtream-job-name found
I am sure that this job exists in jenkins and is under the same organization folder as the current one. It is another job that has its own Jenkinsfile.
Please note that this question is specific to the GitHub Organization Plugin which auto-creates and maintains jobs for each repository and branch from your GitHub Organization.
In addition to the above mentioned answers: I wanted to start a job with a simple parameter passed to a second pipeline and found the answer on http://web.archive.org/web/20160209062101/https://dzone.com/refcardz/continuous-delivery-with-jenkins-workflow
So i used:
stage ('Starting ART job') {
build job: 'RunArtInTest', parameters: [[$class: 'StringParameterValue', name: 'systemname', value: systemname]]
}
First of all, it is a waste of an executor slot to wrap the build step in node. Your upstream executor will just be sitting idle for no reason.
Second, from a multibranch project, you can use the environment variable BRANCH_NAME to make logic conditional on the current branch.
Third, the job parameter takes an absolute or relative job name. If you give a name without any path qualification, that would refer to another job in the same folder, which in the case of a multibranch project would mean another branch of the same repository.
Thus what you meant to write is probably
if (env.BRANCH_NAME == 'master') {
build '../other-repo/master'
}
You can use the build job step from Jenkins Pipeline (Minimum Jenkins requirement: 2.130).
Here's the full API for the build step: https://jenkins.io/doc/pipeline/steps/pipeline-build-step/
How to use build:
job: Name of a downstream job to build. May be another Pipeline job, but more commonly a freestyle or other project.
Use a simple name if the job is in the same folder as this upstream Pipeline job;
You can instead use relative paths like ../sister-folder/downstream
Or you can use absolute paths like /top-level-folder/nested-folder/downstream
Trigger another job using a branch as a param
At my company many of our branches include "/". You must replace any instances of "/" with "%2F" (as it appears in the URL of the job).
In this example we're using relative paths
stage('Trigger Branch Build') {
steps {
script {
echo "Triggering job for branch ${env.BRANCH_NAME}"
BRANCH_TO_TAG=env.BRANCH_NAME.replace("/","%2F")
build job: "../my-relative-job/${BRANCH_TO_TAG}", wait: false
}
}
}
Trigger another job using build number as a param
build job: 'your-job-name',
parameters: [
string(name: 'passed_build_number_param', value: String.valueOf(BUILD_NUMBER)),
string(name: 'complex_param', value: 'prefix-' + String.valueOf(BUILD_NUMBER))
]
Trigger many jobs in parallel
Source: https://jenkins.io/blog/2017/01/19/converting-conditional-to-pipeline/
More info on Parallel here: https://jenkins.io/doc/book/pipeline/syntax/#parallel
stage ('Trigger Builds In Parallel') {
steps {
// Freestyle build trigger calls a list of jobs
// Pipeline build() step only calls one job
// To run all three jobs in parallel, we use "parallel" step
// https://jenkins.io/doc/pipeline/examples/#jobs-in-parallel
parallel (
linux: {
build job: 'full-build-linux', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
},
mac: {
build job: 'full-build-mac', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
},
windows: {
build job: 'full-build-windows', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
},
failFast: false)
}
}
Or alternatively:
stage('Build A and B') {
failFast true
parallel {
stage('Build A') {
steps {
build job: "/project/A/${env.BRANCH}", wait: true
}
}
stage('Build B') {
steps {
build job: "/project/B/${env.BRANCH}", wait: true
}
}
}
}
The command build in pipeline is there to trigger other jobs in jenkins.
Example on github
The job must exist in Jenkins and can be parametrized.
As for the branch, I guess you can read it from git
Use build job plugin for that task in order to trigger other jobs from jenkins file.
You can add variety of logic to your execution such as parallel ,node and agents options and steps for triggering external jobs. I gave some easy-to-read cookbook example for that.
1.example for triggering external job from jenkins file with conditional example:
if (env.BRANCH_NAME == 'master') {
build job:'exactJobName' , parameters:[
string(name: 'keyNameOfParam1',value: 'valueOfParam1')
booleanParam(name: 'keyNameOfParam2',value:'valueOfParam2')
]
}
2.example triggering multiple jobs from jenkins file with conditionals example:
def jobs =[
'job1Title'{
if (env.BRANCH_NAME == 'master') {
build job:'exactJobName' , parameters:[
string(name: 'keyNameOfParam1',value: 'valueNameOfParam1')
booleanParam(name: 'keyNameOfParam2',value:'valueNameOfParam2')
]
}
},
'job2Title'{
if (env.GIT_COMMIT == 'someCommitHashToPerformAdditionalTest') {
build job:'exactJobName' , parameters:[
string(name: 'keyNameOfParam3',value: 'valueOfParam3')
booleanParam(name: 'keyNameOfParam4',value:'valueNameOfParam4')
booleanParam(name: 'keyNameOfParam5',value:'valueNameOfParam5')
]
}
}

Resources