Step expected in Jenkins Groovy script - jenkins

I am having below groovy script for my Jenkins pipeline. But when running its giving error as step expected where my script already having step. Can anyone suggest what's wrong here..
Script file
pipeline {
agent any
stages {
stage('Workspace Preparation') {
steps {
sh """
rm -rf ${workspace}/*
"""
}
}
stage('Get Deployment files') {
steps {
dir("${workspace}/deployfiles") {
if("${params.componentType}"=="A") {
echo "A component deployment"
checkout(## necessary step)
}
else if ("${params.componentType}"=="B") {
echo "B component deployment"
checkout(## necessary step)
}
else {
echo "Invalid"
}
}
}
}
}
}
Getting error as
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 19: Expected a step # line 14, column 6.
if("${params.componentType}"=="A") {
^
enter code here
enter code here

You are missing a script-block.
(Source)
Such a block gives you acces to execute groovy code (for, if-else etc. etc.)
stage('Check') {
steps {
script { // Allows to execute groovy code
dir (...) {
if (...)
}
}
}
See also: How to fix Pipeline-Script “Expected a step” error

Related

How to use artifactResolver in Jenkinsfile pipeline steps?

I am trying to use artifactResolver in a Jenkins pipeline step. However, it is failing.
Trying the following config:
pipeline {
agent any
stages {
stage('Download artifact') {
steps {
artifactResolver {
artifacts {
artifact {
groupId('ch.qos.logback')
artifactId('logback-classic')
version('1.1.1')
classifier('sources')
}
}
}
}
}
}
}
However, I get the following error when I build on Jeninks:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 7: Missing required parameter: "artifacts" # line 7, column 17.
artifactResolver {
^

Declarative pipeline to check the build step = Failure then trigger next build step, but not fail the job.

I am trying to fail a build step in Jenkinsfile with failed results = failure. Once the step is failed it triggers my rollback job. Tried many different things, but had no luck. Any help would be greatly appreciated.
pipeline {
agent any
stages {
stage('Git Checkout') {
steps {
script {
git 'somegit-repo'
sh'''
mvn package
'''
echo currentBuild.result
catchError {
build 'rollback'
}
}
}
}
}
One way is to use a shell script and with exit 1 statement
e.g.
sh "exit 1"
Or you can use error step
error('Failing build because...')
See https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/#error-error-signal
Use a try catch block
node {
stage("Run scripts") {
try {
<some command/script>
} catch (error) {
<rollback command/script>
}
}
}
Thank you so much. This seems to work!
stages {
stage("some test") {
steps{
script {
git 'mygitrepo.git'
try {
sh''' mvn test '''
} catch (error) {
script {
def job = build job: 'rollback-job'
}
}
}
}
}
If you check the cleaning and notifications page
You can do a post step and get rid of all the try/catch stuff and get a cleaner Jenkinsfile
pipeline {
agent any
stages {
stage('No-op') {
steps {
sh 'ls'
}
}
}
post {
always {
echo 'One way or another, I have finished'
deleteDir() /* clean up our workspace */
}
success {
echo 'I succeeeded!'
}
unstable {
echo 'I am unstable :/'
}
failure {
echo 'I failed :('
}
changed {
echo 'Things were different before...'
}
}
}

Jenkinsfile Pipeline errors: “expected a step” and “undefined section”

Can anyone explain why I get the following errors, and what can be a possible solution for them?
Running in Durability level: MAX_SURVIVABILITY
org.codehaus.groovy.control.MultipleCompilationErrorsException:
startup failed: WorkflowScript: 43: Expected a step # line 43, column
17.
if (isUnix()) {
^
WorkflowScript: 71: Undefined section "success" # line 71, column 5.
success {
^
WorkflowScript: 78: Undefined section "failure" # line 78, column 5.
failure {
^
WorkflowScript: 16: Tool type "maven" does not have an install of
"MAVEN_HOME" configured - did you mean "Maven M2"? # line 16, column
19.
maven "MAVEN_HOME"
^
WorkflowScript: 17: Tool type "jdk" does not have an install of
"JAVA_HOME" configured - did you mean "null"? # line 17, column 17.
jdk "JAVA_HOME"
^
The code in the Jenkinsfile is as follows:
pipeline {
// agent defines where the pipeline will run.
agent {
// Here we define that we wish to run on the agent with the label SL202_win
label "SL202_win"
}
// The tools directive allows you to automatically install tools configured in
// Jenkins - note that it doesn't work inside Docker containers currently.
tools {
// Here we have pairs of tool symbols (not all tools have symbols, so if you
// try to use one from a plugin you've got installed and get an error and the
// tool isn't listed in the possible values, open a JIRA against that tool!)
// and installations configured in your Jenkins master's tools configuration.
maven "MAVEN_HOME"
jdk "JAVA_HOME"
}
environment {
// Environment variable identifiers need to be both valid bash variable
// identifiers and valid Groovy variable identifiers. If you use an invalid
// identifier, you'll get an error at validation time.
// Right now, you can't do more complicated Groovy expressions or nesting of
// other env vars in environment variable values, but that will be possible
// when https://issues.jenkins-ci.org/browse/JENKINS-41748 is merged and
// released.
mvnHome = "D:/Tools/apache-maven-3.5.2"
}
stages {
// At least one stage is required.
stage("Preparation") {
// Every stage must have a steps block containing at least one step.
steps {
// Get some code from a GitHub repository
git 'https://git.ceesiesdomain.nl/scm/rsd/test_automation.git'
}
}
stage('Build') {
steps {
// Run the maven build
if (isUnix()) {
sh "'${mvnHome}/bin/mvn' clean test -Dtest=TestRunner"
} else {
bat(/"${mvnHome}\bin\mvn" clean test -Dtest=TestRunner/)
}
}
}
stage('Results') {
steps {
cucumber buildStatus: 'UNSTABLE', failedFeaturesNumber: 999, failedScenariosNumber: 999, failedStepsNumber: 3, fileIncludePattern: '**/*.json', skippedStepsNumber: 999
}
}
}
// Post can be used both on individual stages and for the entire build.
post {
success {
echo "Test run completed succesfully."
}
failure {
echo "Test run failed."
}
always {
// Let's wipe out the workspace before we finish!
deleteDir()
echo "Workspace cleaned"
}
}
success {
mail(from: "jenkins#ceesiesdomain.nl",
to: "ceesie#ceesiesdomain.nl",
subject: "That build passed.",
body: "Nothing to see here")
}
failure {
mail(from: "jenkins#ceesiesdomain.nl",
to: "ceesie#ceesiesdomain.nl",
subject: "That build failed!",
body: "Nothing to see here")
}
// The options directive is for configuration that applies to the whole job.
options {
// For example, we'd like to make sure we only keep 10 builds at a time, so
// we don't fill up our storage!
buildDiscarder(logRotator(numToKeepStr:'10'))
// And we'd really like to be sure that this build doesn't hang forever, so
// let's time it out after an hour.
timeout(time: 60, unit: 'MINUTES')
}
}
I managed to get it working by trimming back all excess and starting with the pure essentials and iteratively adding steps and configs and running it after each change to verify the workings.
The script I ended up with now is:
pipeline {
agent {
label 'SL202_win'
}
stages {
stage("Fetch repository") {
steps {
git 'https://git.ceesiesdomain.nl/scm/rsd/test_automation.git'
}
}
stage('Run test') {
steps {
bat 'cd d:/SL202_Data/workspace/Front-end-SwiftNL/Sanctie_Regressie_Workflows_WCM'
bat 'mvn clean test -f d:/SL202_Data/workspace/Front-end-SwiftNL/Sanctie_Regressie_Workflows_WCM/pom.xml -Dtest=TestRunner'
}
}
}
post {
always {
echo 'Test run completed'
cucumber buildStatus: 'UNSTABLE', failedFeaturesNumber: 999, failedScenariosNumber: 999, failedStepsNumber: 3, fileIncludePattern: '**/*.json', skippedStepsNumber: 999
}
success {
echo 'Successfully!'
}
failure {
echo 'Failed!'
}
unstable {
echo 'This will run only if the run was marked as unstable'
}
changed {
echo 'This will run only if the state of the Pipeline has changed'
echo 'For example, if the Pipeline was previously failing but is now successful'
}
}
options {
timeout(time: 60, unit: 'MINUTES')
}
}
My way is to put the if or for block in a script {} block or dir("") {} block when using declarative pipelines.

Post failure block in Jenkinsfile is not working

I'm trying a post failure action with a parallel step but it never works.
This is my Jenkinsfile:
pipeline {
agent any
stages {
stage("test") {
steps {
withMaven(
maven: 'maven3', // Maven installation declared in the Jenkins "Global Tool Configuration"
mavenSettingsConfig: 'maven_id', // Maven settings.xml file defined with the Jenkins Config File Provider Plugin
mavenLocalRepo: '.repository')
{
// Run the maven build
sh "mvn --batch-mode release:prepare -Dmaven.deploy.skip=true" --> it will always fail
}
}
}
stage("testing") {
steps {
parallel (
phase1: { sh 'echo phase1' },
phase2: { sh "echo phase2" }
)
}
}
}
post {
failure {
echo "FAIL"
}
}
}
But the post failure action here is a bit useles... I don´t see it any place.
Thanks to all!
Regards
I've found the issue, after several hours of searching. What you are missing (and I was missing too) is the catchError section.
pipeline {
agent any
stages {
stage('Compile') {
steps {
catchError {
sh './gradlew compileJava --stacktrace'
}
}
post {
success {
echo 'Compile stage successful'
}
failure {
echo 'Compile stage failed'
}
}
}
/* ... other stages ... */
}
post {
success {
echo 'whole pipeline successful'
}
failure {
echo 'pipeline failed, at least one step failed'
}
}
You should wrap every step that can potentially fail into a catchError function. What this does is:
If an error occurs...
... set build.result to FAILURE...
... and continue the build
The last point is important: your post{ } blocks did not get called because your entire pipeline was aborted before they even had a chance to execute.
Just in case someone else also made the same stupid mistake I did, don't forget the post block needs to be inside the pipeline block.
i.e. This is apparently valid, but (obviously) won't work:
pipeline {
agent { ... }
stages { ... }
}
// WRONG!
post {
always { ... }
}
This is what's correct:
pipeline {
agent { ... }
stages { ... }
post {
always { ... }
}
}

How can I catch any pipeline error in Jenkins?

I have a Jenkins pipeline script that for the most part works fine and I surround most things that will fire a fatal error with try catches. However from time to time really unexpected things happen and I'd like to be able to have a safe catch-all available to do some final reporting before failing the build.
Is there no final default 'stage' I can define that runs whenever an error isn't caught?
Although already been answered for a scripted pipeline I would like to point out that for a declarative pipeline this is done with a post section:
pipeline {
agent any
stages {
stage('No-op') {
steps {
sh 'ls'
}
}
}
post {
always {
echo 'One way or another, I have finished'
deleteDir() /* clean up our workspace */
}
success {
echo 'I succeeeded!'
}
unstable {
echo 'I am unstable :/'
}
failure {
echo 'I failed :('
}
changed {
echo 'Things were different before...'
}
}
}
Each stage can also have it's own section when required.
You can do it by wrapping all your build stages in a big try/catch/finally {} block, for example:
node('yournode') {
try {
stage('stage1') {
// build steps here...
}
stage('stage2') {
// ....
}
} catch (e) {
// error handling, if needed
// throw the exception to jenkins
throw e
} finally {
// some common final reporting in all cases (success or failure)
}
}

Resources