How to disable "build now" option? - jenkins

For a given scripted pipeline(jenkins), the pipeline should only get triggered through webhook from GitLab
Build Now option should be disabled for that pipeline.
Can we configure Jenkins, to disable Build Now option for a specific pipeline script job in jenkins?

EDIT: Here the solution with an scripted Pipeline:
node {
def userIdCause = currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause')
stage("Authorize Usage") {
if (userIdCause.size()) {
error('Aborting Build due to manual start - thats not permitted!')
}
}
}
How about the following solution without any extra plugin on an declarative pipeline:
pipeline {
...
stages {
stage ("Authorize Usage") {
when { expression { getCause() == "USER" } }
steps {
currentBuild.description = 'Aborting Build due to manual start - thats not permitted!'
error('Aborting Build due to manual start - thats not permitted!')
}
}
...
}

Have taken a look at this plug-in supplied on the Jenkin's site? Matrix Authorization Strategy Plugin :
Matrix Strategy
Specifically this sectionL Allow configuring per-agent permissions. This allows e.g. restricting per-agent build permissions when using the Authorize Project plugin (JENKINS-46654)

Not ideal, but if this is a 'freestyle pipeline job'
a quick workaround is to add a build step "Execute shell" as first step. You can use this to prevent a build, when noting has changed.
Every time your sources changes and you push to your repo, a build will have been triggered and as there are changes this script will not exit.
When you click the 'Build now', nothing should have changed in your repo (as the only way it can is through a push which would then trigger a build) it will causes an exit, and fail the build.
if [[ $GIT_COMMIT -eq $GIT_PREVIOUS_COMMIT ]]
then
echo "Exiting build - Nothing has changed"
echo "This is to prevent the usage of Jenkins 'build now'"
exit 1
fi

EDIT: This is the answer to the question of user #mohet in the comments of my other answer because it was to long for the comment section (https://stackoverflow.com/a/55058788/7746963).
The currentBuild variable, which is of type RunWrapper, may be used to refer to the currently running build...
Source: https://opensource.triology.de/jenkins/pipeline-syntax/globals .
hudson.model is the package name of most corresponding core jenkins classes. 'Hudson' because jenkins was once cloned from the codebase of his ancestor named 'hudson'.
You can look up them here: https://javadoc.jenkins.io/hudson/model/package-summary.html .
There you will also find https://javadoc.jenkins.io/hudson/model/Cause.UserIdCause.html . To specify directly the package$classname in some methods like getbuildcauses is the straightforward thought of jenkins dev Team. This reduces the failure potential and makes the code better readable and understandable.

Related

Find artifacts in post-build actions

In a nutshell:
How can I access the location of the produced artifacts within a shell script started in a build or post-build action?
The longer story:
I'm trying to setup a jenkins job to automate the building and propagation of debian packages.
So far, I was already successfull in using the debian-pbuilder plugin to perform the build process, such that jenkins presents the final artifacts after successfully finishing the job:
mypackage_1+020200224114528.NOREV.4_all.deb
mypackage_1+020200224114528.NOREV.4_amd64.buildinfo
mypackage_1+020200224114528.NOREV.4_amd64.changes
mypackage_1+020200224114528.NOREV.4.dsc
mypackage_1+020200224114528.NOREV.4.tar.xz
Now I would like to also automate the deployment process into the local reprepro repository, which would actually just require a simple shell script invocation, I've put together.
My problem: I find no way to determine the artifact location for that deployment script to operate on. The "debian-pbuilder" plugin generates the artifacts in a temporary directory ($WORKSPACE/binaries.tmp15567690749093469649), which changes with every build.
Since the artifacts are listed properly in the finished job status view, I would expect that the artifact details are provided to the script (e.g. by environment variables). But that is obvously not the case.
I've already search extensively for a solution, but didn't find anything helpful.
Or is it me (still somewhat a Rookie in Jenkins), following a wron approach here?
You can use archiveArtifacts. You have binaries.tmp directory in the Workspace and you can use it, but before execute clear workspace using deleteDir().
Pipeline example:
pipeline {
agent any
stages {
stage('Build') {
steps {
deleteDir()
...
}
}
}
post {
always {
archiveArtifacts artifacts: 'binaries*/**', fingerprint: true
}
}
}
You can also check https://plugins.jenkins.io/copyartifact/

Jenkins simple pipeline not triggered by github push

I have created a jenkins pipeline job called "pipelinejob" with the below script:
pipeline {
agent any
stages {
stage ('Setup'){
steps{
//echo "${BRANCH_NAME}"
echo "${env.BRANCH_NAME}"
//echo "${GIT_BRANCH}"
echo "${env.GIT_BRANCH}"
}
}
}
}
Under General, I have selected "GitHub project" and inserted my company's github in the form:
https://github.mycompany.com/MYPROJECTNAME/MY_REPOSITORY_NAME/
Under Build Triggers, i have checked "GitHub hook trigger for GITScm polling
I have created a simple job called "simplejob" with same configuration as 1) and 2)
In my company's Github, i have created a webhook like "jenkins_url/jenkins/github-webhook/"
I commit a change in "mybranch" in "MY_REPOSITORY_NAME"
My simple job "simplejob" is triggered and built successfully
My pipeline job "pipelinejob" is not triggered
In Jenkins log i see the below:
Sep 12, 2019 2:42:45 PM INFO org.jenkinsci.plugins.github.webhook.subscriber.DefaultPushGHEventSubscriber$1 run
Poked simplejob
Nothing regarding my "pipelinejob".
Could you please point me to the right directions as to what to check next?
P.S. I have manually executed my "pipelinejob" successfully
I wasted two days of work on this, as none of the previous solutions worked for me. :-(
Eventually I found the solution on another forum:
The problem is that if you use a Jenkinsfile that is stored in GitHub, along with your project sources, then this trigger must be configured in the Jenkinsfile itself, not in the Jenkins or project configuration.
So add a triggers {} block like this to your Jenkinsfile:
pipeline {
agent any
triggers {
githubPush()
}
stages {
...
}
}
Then...
Push your Jenkinsfile into GitHub
Run one build manually, to let Jenkins know about your will to use this trigger.
You'll notice that the "GitHub hook trigger for GITScm polling" checkbox will be checked at last!
Restart Jenkins.
The next push should trigger an automated build at last!
On the left side-pane of your pipeline job, click GitHub Hook log. If it says 'Polling has not run yet', you will need to manually trigger the pipeline job once before Jenkins registers it to poke on receiving hooks.
Henceforth, the job should automatically trigger on GitHub push events.
I found an answer to this question with scripted pipeline file. We need to declare the Github push event trigger in Jenkins file as follows.
properties([pipelineTriggers([githubPush()])])
node {
git url: 'https://github.com/sebin-vincent/Treasure_Hunt.git',branch: 'master'
stage ('Compile Stage') {
echo "compiling"
echo "compilation completed"
}
stage ('Testing Stage') {
echo "testing completed"
echo "testing completed"
}
stage("Deploy") {
echo "deployment completed"
}
}
}
The declaration should be in the first line.
git url: The URL on which pipeline should be triggered.
branch: The branch on which pipeline should be triggered. When you specify the branch as master and make changes to other branches like develop or QA, that won't trigger the pipeline.
Hope this could help someone who comes here for an answer for the same problem with Jenkins scripted pipeline :-(.
The thing is whenever you create a pipeline job for git push which is to be triggered by github-webhook, first you need to build the pipeline job manually for one time. If it builds successfully, then Jenkins registers it to poke on receiving hooks. And from the next git push, your pipeline job will trigger automatically.
Note: Also make sure that the pipeline job built manually for the first time should be built successfully, otherwise Jenkins will not poke it. If it fails to build, you can never trigger the job again.

Notifications on jenkins job failures - with pipeline from scm

We have several jenkins pipeline jobs setup as "pipeline from scm" that checkout a jenkins file from github and runs it. There is sufficient try/catch based error handling inside the jenkinsfile to trap error conditions and notify the right channels.This blog post goes into a quite a bit of depth about how to achieve this.
However, if there is issue fetching the jenkinsfile in the first place, the job fails silently. How does one generate notifications from general job launch failures before the pipeline is even started?
Jenkins SCM pipeline doesn't have any execution provision similar to catch/finally that will be called if Jenkinsfile load is failed, And I don't think there will be any in future.
However there is this global-post-script which runs groovy script after every build of every job on Jenkins. You have to place that script in $JENKINS_HOME/global-post-script/ directory.
Using this you can send notifications or email to admins based on project that failed and/or reason/exceptions of failure.
Sample code that you can put in script
if ("$BUILD_RESULT" != 'SUCCESS') {
def job = hudson.model.Hudson.instance.getItem("$JOB_NAME")
def build = job.getBuild("$BUILD_NUMBER")
def exceptionsToHandle = ["java.io.FileNotFoundException","hudson.plugins.git.GitException"]
def foundExection = build
.getLog()
.split('\n')
.toList()
.stream()
.filter{ line ->
!line.trim().isEmpty() && !exceptionsToHandle.stream().filter{ex -> line.contains(ex)}.collect().isEmpty()
}
.collect()
.size() > 0;
println "do something with '$foundExection'"
}
You can validate your Jenkinsfile before pushing it to repository.
Command-line Pipeline Linter
There are some IDE Integrations as well
Apparently this is an open issue with Jenkins: https://issues.jenkins.io/browse/JENKINS-57946
I have decided not to use Yogesh answer mentioned earlier. For me it is simpler to just copy the content of the Jenkinsfile directly into the Jenkins project instead of pointing Jenkins to the GIT location of the Jenkinsfile. However, in addition I keep the Jenkinsfile in GIT. But make sure to keep the GIT and the Jenkins version identical.

Jenkins how to create pipeline manual step

Prior Jenkins2 I was using Build Pipeline Plugin to build and manually deploy application to server.
Old configuration:
That works great, but I want to use new Jenkins pipeline, generated from groovy script (Jenkinsfile), to create manual step.
So far I came up with input jenkins step.
Used jenkinsfile script:
node {
stage 'Checkout'
// Get some code from repository
stage 'Build'
// Run the build
}
stage 'deployment'
input 'Do you approve deployment?'
node {
//deploy things
}
But this waits for user input, noting that build is not completed. I could add timeout to input, but this won't allow me to pick/trigger a build and deploy it later on:
How can I achive same/similiar result for manual step/trigger with new jenkins-pipeline as prior with Build Pipeline Plugin?
This is a huge gap in the Jenkins Pipeline capabilities IMO. Definitely hard to provide due to the fact that a pipeline is a single job. One solution might be to "archive" the workspace as an "artifact" (tar and archive **/* as 'workspace.tar.gz'), and then have another pipeline copy the artifact and and untar it into the new workspace. This allows the second pipeline to pickup where the previous one left off. Of course there is no way to gauentee that the second pipeline cannot be executed out of turn or more than once. Which is too bad. The Delivery Pipeline Plugin really shines here. You execute a new pipeline right from the view - instead of the first job. Anyway - not much of an answer - but its the path I'm going to try.
EDIT: This plugin looks promising:
https://github.com/jenkinsci/external-workspace-manager-plugin/blob/master/doc/PIPELINE_EXAMPLES.md

How to go about seeing the branch name of builds in the build history view of Jenkins?

I installed the Feature Branch Notifier Plugin in my instance of Jenkins.
I have checked the "Show full length branch name in the build history view" checkbox at jenkins:8080/configure
I am expecting to see the branch names in build history view, but even after restarting Jenkins I am not seeing the branch names in the build history, as can be seen in the enclosed image.
The project issue queue lists no open issues, and when I try to log in to post an issue, I get the message "Proxy Error - The proxy server received an invalid response from an upstream server. The proxy server could not handle the request POST /account/doSignup. Reason: Error reading from remote server Apache/2.2.14 (Ubuntu) Server at jenkins-ci.org Port 443"
Does anyone know how to go about seeing the branch name of builds in the build history view of Jenkins? Thanks!
Albert.
You can use Build Name Setter Plugin, and set Set Build Name something like #${BUILD_NUMBER} - ${GIT_BRANCH}.
Build-Name-setter-plugin no longer works. I tried on 2.319.1, and the setting never appears in the pipline.
The solution I found is to use the build environment variables to apply to your display name for the build in a step script.
Adjust your Jenkinsfile to pull the branch name as a environmental variable (I am using CURRENT_BRANCH_NAME). Then I created a new stage / step, that runs before any other, and ran a script to adjust the displayname there:
pipeline {
agent {any}
environment {
CURRENT_BRANCH_NAME = "${GIT_BRANCH.split('/').size() > 1 ? GIT_BRANCH.split('/')[1..-1].join('/') : GIT_BRANCH}"
}
stages {
stage('Set branch name') {
steps {
script{
currentBuild.displayName = "#"+currentBuild.number+": "+CURRENT_BRANCH_NAME
}
}
}
stages {
stage('Ok now start doing testing') {
steps {
sh '''#!/bin/bash
echo "Im gona test everything"
'''
}
}
}
}
Now when your Jenkins test starts to build, the name will update once the step is complete.
Note: this solution was tested in a single pipeline (not multi-pipeline), and was for a SCM repo integration.
Sources:
Get git branch name in Jenkins Pipeline/Jenkinsfile
https://sleeplessbeastie.eu/2021/01/29/how-to-define-build-name-and-description-in-jenkins/

Resources