withCredentials() block jenkinsfile syntax error - jenkins

The withCredentials block syntax is confusing me. I have tried placing it outside stages{}, outside stage('saving stross...'), and now within the stage('saving stross...'), but I am unable to fix this syntax error in the jenkins pipeline.
jenkinsfile:
pipeline {
agent {
node {
label 'node1'
}
}
stages {
stage('saving stross token and printing') {
withCredentials([string(credentialsId: 'devadrita-stross', variable: 'deva-stross')]) {
steps {
script {
bat """
python -u C://Users//Administrator//Desktop//stross//stross-script.py, token = "${deva-stross}"
"""
}
}
}
}
}
}
error-
Started by user admin
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 8: Unknown stage section "withCredentials". Starting with version 0.5, steps in a stage must be in a ‘steps’ block. # line 8, column 9.
stage('saving stross token and printing') {
^
WorkflowScript: 8: Expected one of "steps", "stages", or "parallel" for stage "saving stross token and printing" # line 8, column 9.
stage('saving stross token and printing') {
^

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 {
^

Step expected in Jenkins Groovy script

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

How to add try catch block in Jenkins declarative syntax.?

I am trying to add try catch block in Jenkins declarative pipeline but I end up with the following error, I read the document on adding try catch block for scripted pipeline syntax of Jenkins(https://jenkins.io/doc/book/pipeline/syntax/#post-conditions) but I didn't get anything on declarative syntax.
pipeline {
agent any
stages {
try {
stage('Checkout') {
steps {
script {
if (ci_branches.contains(env.BRANCH_NAME)) {
// Pull the code from bitbucket repository
checkout scm
}
}
}
}
}
catch(all) {
currentBuild.result='FAILURE'
}
}
}
Jenkins ci build result
[Bitbucket] Build result notified
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 36: Expected a stage # line 36, column 13.
try {
^
WorkflowScript: 35: No stages specified # line 35, column 9.
stages {
^
Try/catch should be inside a script when using declarative pipeline syntax. Test the following:
pipeline {
agent any
stages {
stage('Checkout') {
steps {
script {
try {
if (ci_branches.contains(env.BRANCH_NAME)) {
// Pull the code from bitbucket repository
checkout scm
}
}
catch(all) {
currentBuild.result='FAILURE'
}
}
}
}
}
}

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.

Jenkinsfile Pipeline errors: "expected a symbol" and "undefined section"

Can anyone explain why I get the following errors, and what can be a possible solution for them?
org.codehaus.groovy.control.MultipleCompilationErrorsException:
startup failed: WorkflowScript: 20: Expected a symbol # line 20,
column 4.
environment {
WorkflowScript: 17: Undefined section "error" # line 17, column 1.
pipeline {
The code in the Jenkinsfile is as follows:
#!groovy
def application, manifest, git, environment, artifactory, sonar
fileLoader.withGit('git#<reducted>', 'v1', 'ssh-key-credential-id-number') {
application = fileLoader.load('<reducted>');
manifest = fileLoader.load('<reducted>');
git = fileLoader.load('<reducted>');
environment = fileLoader.load('<reducted>');
}
pipeline {
agent { label 'cf_slave' }
environment {
def projectName = null
def githubOrg = null
def gitCommit = null
}
options {
skipDefaultCheckout()
}
stages {
stage ("Checkout SCM") {
steps {
checkout scm
script {
projectName = git.getGitRepositoryName()
githubOrg = git.getGitOrgName()
gitCommit = manifest.getGitCommit()
}
}
}
stage ("Unit tests") {
steps {
sh "./node_modules/.bin/mocha --reporter mocha-junit-reporter --reporter-options mochaFile=./testResults/results.xml"
junit allowEmptyResults: true, testResults: 'testResults/results.xml'
}
}
//stage ("SonarQube analysis") {
//...
//}
// stage("Simple deploy") {
// steps {
// // Login
// sh "cf api <reducted>"
// sh "cf login -u <reducted> -p <....>"
//
// // Deploy
// sh "cf push"
// }
// }
}
post {
// always {
// }
success {
sh "echo 'Pipeline reached the finish line!'"
// Notify in Slack
slackSend color: 'yellow', message: "Pipeline operation completed successfully. Check <reducted>"
}
failure {
sh "echo 'Pipeline failed'"
// Notify in Slack
slackSend color: 'red', message: "Pipeline operation failed!"
//Clean the execution workspace
//deleteDir()
}
unstable {
sh "echo 'Pipeline unstable :-('"
}
// changed {
// sh "echo 'Pipeline was previously failing but is now successful.'"
// }
}
}
Your Pipeline is mostly fine — adding Scripted Pipeline elements before the Declarative pipeline block is generally not a problem.
However, at the very start, you're defining an variable called environment (and git), which are basically overriding the elements declared by the various Pipeline plugins.
i.e. When you attempt to do pipeline { environment { … } }, the environment is referring to your variable declaration, which causes things to go wrong.
Rename those two variables, and you'll fix the first error message.
To fix the second error message, remove the attempts to declare variables from the environment block — this block is only intended for exporting environment variables for use during the build steps, e.g.:
environment {
FOO = 'bar'
BAR = 'baz'
}
The script block you have will work fine without these declarations. Alternatively, you can move those variable declarations to the top level of your script.
If you're using declarative pipeline (which you are, e.g. the outer pipeline step), then you may only declare the pipeline on the outer layer, e.g. you can't have variable and function definitions. This is the downside of using declarative pipeline.
More info here
As I see it you can solve this the following ways:
Use scripted pipeline instead
Move the code at the beginning to a global pipeline library (Might be tricky to solve variable scoping if a value is used in several places, but it should be doable.
Move the code at the beginning to an script step inside the pipeline and store the values as described here.

Resources