Want to move the entire post steps in Jenkins Global Shared library - jenkins

I am new to Jenkins and I want to use Jenkins shared library for my post build steps so that I don't have to write them again and again but the problem is when I call my groovy method in the post section of the pipeline it gives the following error.
WorkflowScript: 12: The ‘post’ section can only contain build condition names with code blocks. Valid condition names are [always, changed, fixed, regression, aborted, success, unsuccessful, unstable, failure, notBuilt, cleanup] # line 12, column 9.
build()
^
WorkflowScript: 11: post can not be empty # line 11, column 5.
post {
^
2 errors
My pipeline syntax:
#Library("new-library") _
pipeline {
agent any
stages {
stage('Hello') {
steps {
echo 'Hello world!'
}
}
}
post {
build()
}
}
build is the name of the groovy file.
My groovy file which is on GitHub
def call() {
always {
echo 'This will always run'
}
success {
echo 'This will run only if successful'
}
unstable {
echo 'This will run only if run was marked as unstable'
}
changed {
echo 'This will run only if the state of the pipeline is changed'
echo 'FOR EXAMPLE, if the pipeline was previously failed but not it is successful'
}
}
Simply I want my post steps to be trigger from the Global Shared Library. If there is some other method do let me know as well.
Thank you in advance.

Related

Jenkins post actions on stage level are influenced by buildResult

In my jenkins pipeline i have several post-success actions in different stages that define environment variables depending on the stage results (in success case). I am also using parallel and sequential stages, but i do not believe this is affecting the result. Below is a trimmed excerpt:
stage('stage1') {
agent {
label 'agent1'
}
when {
expression {
return Jenkins.instance.getItem("${'job1'}").isBuildable()
}
environment name: 'job0', value: 'success'
}
steps {
catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
build job: 'job1'
}
}
post {
success {
script {
env.job1 = "success"
echo "job1: ${env.job1} !"
}
}
}
}
Now whenever the build result is set to FAILURE within a stage by catchError, all post actions in other stages do not evaluate the related stage result, but the build result instead, which i do not want (and believe they should not do), referring to https://www.jenkins.io/doc/book/pipeline/syntax/#post :
The post section defines one or more additional steps that are run upon the completion of a Pipeline’s or stage’s run (depending on the location of the post section within the Pipeline)
But in my case, after the first error no more stage level post-success actions are executed..
My workaround so far is to modify catcherror, add a post-failure action that sets another variable which is evaluated in the very last stage to set the build result:
stage('stage1') {
steps {
catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
build job: 'job1'
}
}
post {
success { .. }
failure {
script {
env.testFail = "true"
echo "testFail: ${testFail} !"
}
}
}
}
..
stage('set buildResult') {
when {
environment name: 'testFail', value: 'true'
}
steps {
script {
bat '''
echo "testFail variable found. Changing buildresult to FAILURE."
exit 1
'''
}
}
}
Is there anything I missed in the docs, or can anybody confirm this behavior? I would appreciate to remove my workaround and let the catchError do all the work for me.
I have already searched through official docs and mailing list, including jenkins issues, but have not found information about this issue anywhere.
This is my first time contributing to stackoverflow, so please forgive me if I made mistakes or did not express myself clearly (leaving reader-only mode).
Jenkins - v2.204.2
Pipeline - v2.6
Pipeline Declarative - v1.8.4

Jenkins Pipeline - How to fix syntax error in matrix section?

I've been trying to configure a matrix section in a declarative pipeline, but it keeps failing.
In the official documentation, it states:
Stages in Declarative Pipeline may have a matrix section defining a multi-dimensional matrix of name-value combinations to be run in parallel.
This is my (simplified) pipeline:
pipeline {
agent { label 'production-linux' } // Set where this project can run
stages {
stage("do something") {
matrix {
axes {
axis {
name 'foo'
values 'bar1', 'bar2', 'bar3'
}
}
stages{
stage("using $foo"){
steps{
step {
echo "using variable: $foo"
}
}
}
}
}
}
}
}
But when I run it, I get the following:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 14: Unknown stage section "matrix". Starting with version 0.5, steps in a stage must be in a ‘steps’ block. # line 14, column 9.
stage("do something") {
^
WorkflowScript: 14: Expected one of "steps", "stages", or "parallel" for stage "do something" # line 14, column 9.
stage("do something") {
^
Has the Matrix section been deprecated?
Has the Matrix section been deprecated?
No it has not. The exception tells that it found a syntax error.
Your syntax error appears here:
steps{
step {
echo "using variable: $foo"
}
}
Quoting the official documentation:
The steps section defines a series of one or more steps to be executed
in a given stage directive.
Unfortunately there is no step-keyword directly, every command you execute in the steps is basically a step. To fix your syntax error try the following:
steps{
echo "using variable: $foo"
}

My jenkinsfile does not compile anymore when trying to add a post build action

My jenkinsfile does not compile anymore when trying to add a POST action. This last one should be displayed to the jenkins console output at the end of build.
Part I is about my jenkinsfile code for which builds are done well.
Part II is the patch added to part I for which any builds fail.
I want to integrate part I and part II to get the expected output described hereafter but integration fails whatever how insertion is made.
I have tried a lot of thing and i'm stucked now, so any help will be appreciate.
// Part I : my base code
node {
def mvnHome
stage('Preparation') {
git 'https://github.com/jglick/simple-maven-project-with- tests.git'
// Get the Maven tool.
// ** NOTE: This 'M3' Maven tool must be configured
// ** in the global configuration.
mvnHome = tool 'M3'
}
stage('Build') {
// Run the maven build
if (isUnix()) {
sh "'${mvnHome}/bin/mvn' -Dmaven.test.failure.ignore clean package"
} else {
bat(/"${mvnHome}\bin\mvn" -Dmaven.test.failure.ignore clean package/)
}
}
stage('Results') {
junit '**/target/surefire-reports/TEST-*.xml'
archiveArtifacts 'target/*.jar'
}
}
// Part II : code to add to the previous code
post {
always {
echo 'I have finished and deleting workspace'
// deleteDir()
}
success {
echo 'Job succeeeded!
}
unstable {
echo 'I am unstable :/'
}
failure {
echo 'I failed :('
}
changed {
echo 'Things were different before...'
}
}
output expected in the console output : 'Job succeeeded! or I am unstable :/ or 'I failed :(' ... depending on the jenkins build status and always clean the workspace before each new build
Actual result is the error message from the console output :
java.lang.NoSuchMethodError: No such DSL method 'post' found among steps [archive, bat, build, catchError, checkout, deleteDir, dir ......
You are mixing up scripted and declarative pipeline syntax. post is part of declarative, but you use the scripted variant (no pipeline, but node steps).
You have to use try/catch.
See the documentation.

Build only when a file contains specific text

I would like to know how to continue with a build only when a file contains specific text?
I want the build to fail if the text is incorrect, otherwise continue with build.
update your script to return a nonzero exit status when the file doesn't contain the text. run your shell script via an sh step like this:
sh '/path/to/your/script_that_checks_another_file_for_certain_text.sh'
full pipeline:
pipeline {
agent { label 'docker' }
stages {
stage('build') {
steps {
sh '/path/to/your/script_that_checks_another_file_for_certain_text.sh'
echo 'this will not happen if the above script returns a bad exit status'
}
}
}
}

Jenkins pipeline - try catch for particular stage and subsequent conditional step

I'm trying to replicate the equivalent of a conditional stage in Jenkins pipeline using a try / catch around a preceding stage, which then sets a success variable, which is used to trigger the conditional stage.
It appears that a try catch block is the way to go, setting a success var to SUCCESS or FAILED, which is used as part of a when statement later (as part of the conditional stage).
The code I am using is as follows:
pipeline {
agent any
stages {
try{
stage("Run unit tests"){
steps{
sh '''
# Run unit tests without capturing stdout or logs, generates cobetura reports
cd ./python
nosetests3 --with-xcoverage --nocapture --with-xunit --nologcapture --cover-package=application
cd ..
'''
currentBuild.result = 'SUCCESS'
}
}
} catch(Exception e) {
// Do something with the exception
currentBuild.result = 'SUCCESS'
}
stage ('Speak') {
when {
expression { currentBuild.result == 'SUCCESS' }
}
steps{
echo "Hello, CONDITIONAL"
}
}
}
}
The latest syntax error I am receiving is as follows:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup
failed:
WorkflowScript: 4: Expected a stage # line 4, column 9.
try{
I've also tried lots of variations.
Am I taking the wrong approach here? This seems like a fairly common requirement.
Thanks.
This might solve your problem depending on what you are going for. Stages are only run when the preceding stages succeed, so if you actually have two stages like in your example, and if you want the second to only run when the first succeeds, you want to ensure that the first stage fails appropriately when tests fail. Catching will prevent the (desirable) failure. Finally will preserve the failure, and can also still be used to grab your test results.
So here, the second stage will only run when the tests pass, and the test results will be recorded regardless:
pipeline {
agent any
stages {
stage("Run unit tests"){
steps {
script {
try {
sh '''
# Run unit tests without capturing stdout or logs, generates cobetura reports
cd ./python
nosetests3 --with-xcoverage --nocapture --with-xunit --nologcapture --cover-package=application
cd ..
'''
} finally {
junit 'nosetests.xml'
}
}
}
}
stage ('Speak') {
steps{
echo "Hello, CONDITIONAL"
}
}
}
}
Note that I'm actually using try in a declarative pipeline, but like StephenKing says, you can't just use try directly (you have to wrap arbitrary groovy code in the script step).

Resources