Jenkins - How to run a stage/function before pipeline starts? - jenkins

We are using a Jenkins multibranch pipeline with BitBucket to build pull request branches as part of our code review process.
We wanted to abort any queued or in-progress builds so that we only run and keep the latest build - I created a function for this:
def call(){
def jobName = env.JOB_NAME
def buildNumber = env.BUILD_NUMBER.toInteger()
def currentJob = Jenkins.instance.getItemByFullName(jobName)
for (def build : currentJob.builds){
def exec = build.getExecutor()
if(build.isBuilding() && build.number.toInteger() != buildNumber && exec != null){
exec.interrupt(
Result.ABORTED,
new CauseOfInterruption.UserInterruption("Job aborted by #${currentBuild.number}")
)
println("Job aborted previously running build #${build.number}")
}
}
}
Now in my pipeline, I want to run this function when the build is triggered by the creation or push to a PR branch.
It seems the only way I can do this is to set the agent to none and then set it to the correct node for each of the subsequent stages. This results in missing environment variables etc. since the 'environment' section runs on the master.
If I use agent { label 'mybuildnode' } then it won't run the stage until the agent is free from the currently in-progress/running build.
Is there a way I can get the 'cancelpreviousbuilds()' function to run before the agent is allocated as part of my pipeline?
This is roughly what I have currently but doesn't work because of environment variable issues - I had to do the skipDefaultCheckout so I could do it manually as part of my build:
pipeline {
agent none
environment {
VER = '1.2'
FULLVER = "${VER}.${BUILD_NUMBER}.0"
PROJECTPATH = "<project path>"
TOOLVER = "2017"
}
options {
skipDefaultCheckout true
}
stages {
stage('Check Builds') {
when {
branch 'PR-*'
}
steps {
// abort any queued/in-progress builds for PR branches
cancelpreviousbuilds()
}
}
stage('Checkout') {
agent {
label 'buildnode'
}
steps {
checkout scm
}
}
}
}
It works and aborts the build successfully but I get errors related to missing environment variables because I had to start the pipeline with agent none and then set each stage to agent label 'buildnode' to.
I would prefer that my entire pipeline ran on the correct agent so that workspaces / environment variables were set correctly but I need a way to trigger the cancelpreviousbuilds() function without requiring the buildnode agent to be allocated first.

You can try combining the declarative pipeline and the scripted pipeline, which is possible.
Example (note I haven't tested it):
// this is scripted pipeline
node('master') { // use whatever node name or label you want
stage('Cancel older builds') {
cancel_old_builds()
}
}
// this is declarative pipeline
pipeline {
agent { label 'buildnode' }
...
}
As a small side comment, you seem to use: build.number.toInteger() != buildNumber which would abort not only older builds but also newer ones. In our CI setup, we've decided that it's best to abort the current build if a newer build has already been scheduled.

Related

How to get jenkins multibranch pipeline last build revision?

I have jenkins pipeline and also using a shared library for jenkins.
In my multibranch pipeline three to four repo clone while executing build using bitbucket plugin.
my question is how to get the last build revision from the previous build.
I have tried currentBuild.changeSets approach but for multiple repositories clone, it fails.
I had to get SCM revisions from the previous builds too. I didn't find any API to get it nicely, so I implemented a workaround. It is not great, but at least it works ;-)
When you save an environment variable by using env.setProperty(name, value) it is saved in the build metadata as a build variable. You can read it at any moment.
pipeline {
agent any
stages {
stage('Test') {
script {
env.setProperty('MY_ENV', env.BUILD_NUMBER)
def previousBuild = currentBuild.previousBuild
if (previousBuild != null) {
echo previousBuild.buildVariables['MY_ENV'] // prints env.BUILD_NUMBER - 1
}
}
}
}
}
In your case you have 4 checkouts. I don't know how you close sources, so let's imagine that you have a cloneRepo method and it sets the GIT_COMMIT environment variable. They you may use:
def previousBuild = currentBuild.previousBuild
if (previousBuild != null) {
echo previousBuild.buildVariables['GIT_COMMIT_REPO_1']
echo previousBuild.buildVariables['GIT_COMMIT_REPO_2']
echo previousBuild.buildVariables['GIT_COMMIT_REPO_3']
echo previousBuild.buildVariables['GIT_COMMIT_REPO_4']
}
cloneRepo(repo1)
env.setProperty('GIT_COMMIT_REPO_1', env.GIT_COMMIT)
cloneRepo(repo2)
env.setProperty('GIT_COMMIT_REPO_2', env.GIT_COMMIT)
cloneRepo(repo3)
env.setProperty('GIT_COMMIT_REPO_3', env.GIT_COMMIT)
cloneRepo(repo4)
env.setProperty('GIT_COMMIT_REPO_4', env.GIT_COMMIT)
If you use the checkout step, then you may do:
def commitId = checkout(scm).find { it.key == 'GIT_COMMIT' }
env.setProperty('GIT_COMMIT_REPO_1', commitId)

Jenkins: Schedule Particular Stage with single pipeline

I have a single pipeline where it' declarative and I've several stages such as below triggers via webhook.
I would like to execute and scheduled Stage B at a certain time which can also run without trigger via webhook. Clearly it needs to run when triggers via webhook and also run when it will be schedule. Can I handle this without creating seperate job or pipeline in Jenkins ?
stage('A'){
when{
beforeAgent true
expression{return env.GIT_BRANCH == "origin/development"}
}
steps{
script{
//Do something
}
stage ('B'){
when {
beforeAgent true
expression{return env.GIT_BRANCH == "origin/development"}
steps {
script {
//Run Tests
}
}
}
stage('C'){
when{
beforeAgent true
expression{return env.GIT_BRANCH == "origin/development"}
}
steps{
script{
//Do something
}
You can discover what caused your pipeline to run. This may be cron trigger, manual trigger, code commit trigger, webhook trigger, comment on GitHub, upstream job, etc. (depending on plugins installed, the list may be long.)
Here's and example of code to understand what the trigger was. This example sets the environment variable TRIGGERED_BY.
def checkForTrigger() {
def timerCause = currentBuild.rawBuild.getCause(hudson.triggers.TimerTrigger.TimerTriggerCause)
if (timerCause) {
echo "Build reason: Build was started by timer"
env.TRIGGERED_BY = 'timer'
return
}
def userCause = currentBuild.rawBuild.getCause(hudson.model.Cause$UserIdCause)
if (userCause) {
echo "Build reason: Build was started by user"
env.TRIGGERED_BY = 'user'
return
}
def remoteCause = currentBuild.rawBuild.getCause(hudson.model.Cause$RemoteCause)
if (remoteCause) {
echo "Build reason: Build was started by remote script"
env.TRIGGERED_BY = 'webhook'
return
}
// etc.
println "We haven't caught any of triggers, might be a new one, here is the dump"
def causes = currentBuild.rawBuild.getCauses()
println causes.dump()
}
I think that a build might have more than one trigger, if so the order of your clauses is important.
Once you have this figured out, you can run your stages only when the trigger fits your definition.
stage ('B'){
when {
beforeAgent true
anyOf {
expression{return env.GIT_BRANCH == "origin/development"}
environment name: 'TRIGGERED_BY', value: 'timer'
environment name: 'TRIGGERED_BY', value: 'webhook'
}
Not in a clean or first-class manner, but yes you can do it effectively.
For any job which has been run at least once, you can click "replay" for the previous run.
You will then be presented with the Jenkinsfile in a text edit box. At this point you can perform any edit you want to the Jenkinsfile (including pasting in a completely unrelated Jenkinsfile if you wanted) and Jenkins will execute the modified version. For your specific case, you can delete all the stages you don't want to re-run and just leave behind the one (or two, etc) you want.

Is there a way to secure a closure in Jenkins pipeline?

I am currently working on a generic pipeline which is going to be used via shared library to replace existing jobs so that it's easier to manage all jobs from a more centralized place. Most of the existing jobs have these three stages:
allocates a node
checks out the code from git repository and builds it
deploys the code to a testing repository
Some of the jobs have a few if/elses in their stages which do things based on parameters or environment variables, but overall the jobs are quite similar otherwise. The solution which comes to my mind is to use Closures to allow for additional logic code to be executed in those stages, but I am having difficulties figuring out how to secure this so that the only possible "steps" you can execute are sh and bat.
Here is an oversimplified example vars/genericPipeline.groovy to illustrate what I'm talking about:
def call(body)
{
def config = [:]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = config
body()
String AGENT_LABEL = config.getOrDefault('label', 'mvn3')
Closure MVN_BUILD = config.getOrDefault('build', {
sh "mvn clean install"
})
Closure MVN_DEPLOY = config.getOrDefault('deploy', { BRANCH_NAME, ARTIFACT_COORDINATES, SERVER_ID, REPO, TMP_REPO ->
def SERVER_URL = REPO
if (BRANCH_NAME != 'master')
{
SERVER_URL = TMP_REPO
}
sh label: "Deploying ${ARTIFACT_COORDINATES}",
script: "mvn deploy" +
" -DskipTests" +
" -DaltDeploymentRepository=${SERVER_ID}::default::${SERVER_URL}"
})
pipeline {
agent {
node {
label AGENT_LABEL
}
}
environment {
GROUP_ID = readMavenPom().getGroupId()
ARTIFACT_ID = readMavenPom().getArtifactId()
VERSION = readMavenPom().getVersion()
ARTIFACT_COORDINATES = "${readMavenPom().getGroupId()}:${readMavenPom().getArtifactId()}:${readMavenPom().getVersion()}"
}
stages {
stage('Building...') {
steps {
MVN_BUILD()
}
}
stage('Deploying...') {
steps {
MVN_DEPLOY(BRANCH_NAME, env.ARTIFACT_COORDINATES, config.serverId, config.repo, config.tmpRepo)
}
}
}
}
}
This could later be used in the jobs as:
genericPipeline {
build = {
sh "mvn clean install"
}
// could be set for the "corner cases" or could skipped to use the
// default deploy closure for all other cases.
deploy = {
sh "mvn deploy"
}
}
As you can see, the deploy uses two different repositories to deploy to, based on the branch name. I am aware I could simply just put the logic in the stage, but the problem is that some of the jobs are not multi-branch and they would not have this if/else logic. However they would still have the same pipeline structure without any other changes and I would prefer to have to maintain one pipeline than 5 relatively similar pipes for all the different if/else cases which could occur in the deploy stage. :)
So, the question here - is it possible to only white-list the execution of specific steps (i.e. sh/bat) in the MVN_BUILD and MVN_DEPLOY closures? Or if there is another, perhaps even better way to handle this case?

Multiple Jenkinsfiles, One Agent Label

I have a project which has multiple build pipelines to allow for different types of builds against it (no, I don't have the ability to make one build out of it; that is outside my control).
Each of these pipelines is represented by a Jenkinsfile in the project repo, and each one must use the same build agent label (they need to share other pieces of configuration as well, but it's the build agent label which is the current problem). I'm trying to put the label into some sort of a configuration file in the project repo, so that all the Jenkinsfiles can read it.
I expected this to be simple, as you don't need this config data until you have already checked out a copy of the sources to read the Jenkinsfile. As far as I can tell, it is impossible.
It seems to me that a Jenkinsfile cannot read files from SCM until the project has done its SCM step. However, that's too late: the argument to agent{label} is read before any stages get run.
Here's a minimal case:
final def config
pipeline {
agent none
stages {
stage('Configure') {
agent {
label 'master'
}
steps {
checkout scm // we don't need all the submodules here
echo "Reading configuration JSON"
script { config = readJSON file: 'buildjobs/buildjob-config.json' }
echo "Read configuration JSON"
}
}
stage('Build and Deploy') {
agent {
label config.agent_label
}
steps {
echo 'Got into Stage 2'
}
}
}
}
When I run this, I get:
java.lang.NullPointerException: Cannot get property 'agent_label' on null object I don't get either of the echoes from the 'Configure' stage.
If I change the label for the 'Build and Deploy' stage to 'master', the build succeeds and prints out all three echo statements.
Is there any way to read a file from the Git workspace before the agent labels need to be set?
Please see https://stackoverflow.com/a/52807254/7983309. I think you are running into this issue. label is unable to resolve config.agent_label to its updated value. Whatever is set in the first line is being sent to your second stage.
EDIT1:
env.agentName = ''
pipeline {
agent none
stages {
stage('Configure') {
agent {
label 'master'
}
steps {
script {
env.agentName = 'slave'
echo env.agentName
}
}
}
stage('Finish') {
steps {
node (agentName as String) { println env.agentName }
script {
echo agentName
}
}
}
}
}
Source - In a declarative jenkins pipeline - can I set the agent label dynamically?

External workspace manager plugin with declarative pipeline

I want to use the mentioned plugin with a declarative pipeline, to be precise I want to convert the following documentation example to a declarative pipeline:
The pipeline code in the upstream job is the following:
stage ('Stage 1. Allocate workspace in the upstream job')
def extWorkspace = exwsAllocate 'diskpool1'
node ('linux') {
exws (extWorkspace) {
stage('Stage 2. Build in the upstream job')
git url: 'https://github.com/alexsomai/dummy-hello-world.git'
def mvnHome = tool 'M3'
sh '${mvnHome}/bin/mvn clean install -DskipTests'
}
}
And the downstream's Pipeline code is:
stage ('Stage 3. Select the upstream run')
def run = selectRun 'upstream'
stage ('Stage 4. Allocate workspace in the downstream job')
def extWorkspace = exwsAllocate selectedRun: run
node ('test') {
exws (extWorkspace) {
stage('Stage 5. Run tests in the downstream job')
def mvnHome = tool 'M3'
sh '${mvnHome}/bin/mvn test'
}
}
Thanks!
I searched everywhere for a clear answer to this, yet never found a definitive answer. So, I pulled the External Workspace Plugin code and read it. The answer is simple as long as the plugins Model doesn't change.
Anytunc's answer is very close, but the issue is getting the path from the External Workspace Plugin and getting it into the customWorkspace configuration.
What I ended up doing was creating a method:
def getExternalWorkspace() {
extWorkspace = exwsAllocate diskPoolId: "jenkins"
return extWorkspace.getCompleteWorkspacePath()
}
and setting my agent to:
agent {
node {
label 'Linux'
customWorkspace getExternalWorkspace()
}
}
If you'd rather not set the entire pipeline to that path, you could create as many external workspaces as you want, then use
...
steps {
dir(getExternalWorkspace()) {
do fancy stuff
...
}
}
...
You can use this agent directive:
agent {
node {
label 'my-defined-label'
customWorkspace '/some/other/path'
}
}

Resources