Jenkins Pipeline: NoSuchMethodError: No such DSL method 'systemGroovyCommand' found among steps - jenkins-pipeline
I m trying to set jenkins build have a display name, but getting error while adding below steps
ansiColor('xterm') {
timestamps {
node() {
sshagent(['dp_user']) {
systemGroovyCommand('build.displayName = build.properties.environment.BUILD_DISPLAY_NAME ?: build.displayName')
stage('Archive GOStar Bioactivity Logs') {
notifyOnFailure(
"GOSTAR Bioactivity Log Archival Failed",
"Failed to archive logs for ENTITY ${params.ENTITY}",
"FAILED",
params.FAILURE_EMAIL,
{
build(job: 'gostar_bioactivity_logs_archiver', parameters: [
string(name: 'ENTITY', value: params.ENTITY)
]
)
}
)
}
}
}
}
}
def notifyOnFailure(subject, msg, status, list, block) {
try {
block()
} catch (err) {
echo 'Caught error:'
echo msg
echo "Setting build result to ${status}"
currentBuild.result = status
echo 'Cleaning up workspace after catching error'
step([$class: 'WsCleanup'])
echo 'Sending notfication of failure'
notify(subject, msg, list)
echo 'Clearing deployed artifacts from HDFS'
echo 'Throwing error before exiting stage'
throw err
}
}
java.lang.NoSuchMethodError: No such DSL method 'systemGroovyCommand' found among steps [ArtifactoryGradleBuild, MavenDescriptorStep, addInteractivePromotion, ansiColor, archive, artifactoryBuildTrigger, artifactoryDistributeBuild, artifactoryDownload, artifactoryEditProps, artifactoryGoPublish, artifactoryGoRun, artifactoryMavenBuild, artifactoryNpmCi, artifactoryNpmInstall, artifactoryNpmPublish, artifactoryNugetRun, artifactoryPipRun, artifactoryPromoteBuild, artifactoryUpload, bat, build, buildAppend, catchError, checkout, collectEnv, collectIssues, conanAddRemote, conanAddUser, createDockerBuildStep, createReleaseBundle, deleteDir, deleteReleaseBundle, deployArtifacts, dir, distributeReleaseBundle, dockerPullStep, dockerPushStep, dsCreateReleaseBundle, dsDeleteReleaseBundle, dsDistributeReleaseBundle, dsSignReleaseBundle, dsUpdateReleaseBundle, echo, emailext, emailextrecipients, error, fileExists, getArtifactoryServer, getContext, getJFrogPlatformInstance, git, initConanClient, input, isUnix, jfPipelines, jfrogInstance, junit, library, libraryResource, load, lock, mail, milestone, newArtifactoryServer, newBuildInfo, newGoBuild, newGradleBuild, newJFrogPlatformInstance, newMavenBuild, newNpmBuild, newNugetBuild, newPipBuild, node, parallel, powershell, properties, publishBuildInfo, publishChecks, pwd, readFile, readTrusted, resolveScm, retry, rtAddInteractivePromotion, rtBuildAppend, rtBuildInfo, rtBuildTrigger, rtCollectIssues, rtConanClient, rtConanRemote, rtConanRun, rtCreateDockerBuild, rtDeleteProps, rtDockerPull, rtDockerPush, rtDotnetResolver, rtDotnetRun, rtDownload, rtGoDeployer, rtGoPublish, rtGoResolver, rtGoRun, rtGradleDeployer, rtGradleResolver, rtGradleRun, rtMavenDeployer, rtMavenResolver, rtMavenRun, rtNpmCi, rtNpmDeployer, rtNpmInstall, rtNpmPublish, rtNpmResolver, rtNugetResolver, rtNugetRun, rtPipInstall, rtPipResolver, rtPromote, rtPublishBuildInfo, rtServer, rtSetProps,
Related
How can i set the jenkins job to pass when the test are actually failed
I'm trying to do something similar to what this guy is doing: Jenkins failed build: I Want it to pass create a pipeline job in Jenkins for all the Known bugs tests, I want the job to PASS when all the tests are FAILED. while when even 1 test is PASS, the job will be GREEN. I found here this solution stage('Tests') { steps { script{ //running the tests status = sh "${mvnHome}/bin/mvn clean test -e -Dgroups=categories.knownBug" if (status === "MARK-AS-UNSTABLE") { currentBuild.result = "STABLE" } } } } but got an error Unsupported operation in this context # line 47, column 39. if (status === "MARK-AS-UNSTABLE") { ------------EDIT--------- Thanks to #yrc I changed the code to try { sh "${mvnHome}/bin/mvn clean test -e -Dgroups=categories.knownBug" } catch (err) { echo "Caught: ${err}" currentBuild.result = "STABLE" } It did help with the error msg, but I want the job to pass when one of the tests is failing. Now, both test and job has failed
Just wrap your execution with a try-catch block. try { sh "${mvnHome}/bin/mvn clean test -e -Dgroups=categories.knownBug" } catch (err) { echo "Caught: ${err}" currentBuild.result = "STABLE" }
Retry and timeout in Jenkins DSL Pipeline job
I have a logic for deployment on certain environment that I need to retry. And that logic have some timeout too. So I wrote the DSL code as below: Pipeline { stages { stage('Promote To Stage2 Environment') { options { timeout(time: "${env.STAGE_TIME_OUT}", unit: "HOURS") retry("${env.RETRY_COUNT}") } steps { script { //my logic } } } } } Now , I need to perform rollback action and need to terminate pipeline job, in case retry exceeded or timeout exceeded while doing deployment on particular environment. So I modified the code as below: pipeline { stages { stage('Promote To Stage2 Environment') { steps { script { try { timeout(time: "${env.STAGE_TIME_OUT}", unit: "HOURS") { retry("${env.RETRY_COUNT}") { //my logic } } } } catch (err) { //Need rollback. action to be required , in case retry exceeded or timeout happen performRollBack('env') error('Deployment on Stage1 failed..... Build rolled back....') } } } } } Is this is a right way, or something I am missing.
you can also do like below example: pipeline { agent any stages { stage('debug') { options { timeout(time: 10, unit: 'SECONDS') retry(2) } steps { // uncomment below to check post failure sh "exit 1" // uncomment below to check post unsuccessful scenario //sleep 100 } } } post { always { echo 'I will execute always' } failure { echo 'I will execute if a failure occured' } unsuccessful { echo 'I will execute if a job is timedout and failed' } } } Retry scenario the output will be Timeout scenario the output will be you can find more post build action here
Jenkinsfile setting stageResult variable based on conditions
I'm trying to script a Jenkinsfile in Declarative Syntax, requirement here is if set environment variables are not a match then pipeline stage should be depict as "Aborted" but the build status could be either Aborted or unstable, on Jenkins online documentation and from Snippet Generator did see the following style catchError(buildResult: 'ABORTED', stageResult: 'ABORTED') { // some block } catchError does not serve my purpose as it is appropriate for use when the script inside the stage does not return true or if there is an execution error, although default when condition in Jenkins Declarative Syntax is appropriate, Jenkins does not allow setting stage result to 'ABORTED' when { expression { SCM_BRANCH_NAME ==~ /(master|QA)/ } expression{ ENVIRONMENT ==~ /(QA)/ } allOf{ environment ignoreCase: true,name: 'PRODUCT_NAME' , value: 'PRODUCT-1' } } Please view the Sample Jenkinsfile below using if and else format Sample Jenkinsfile pipeline { agent { node { label 'master' } } environment{ ENVIRONMENT = "QA" PRODUCT_NAME = "PRODUCT-1" SCM_BRANCH_NAME = "master" } stages{ stage('Testing-1') { when{ expression{ ENVIRONMENT ==~ /(QA)/ } } steps { script { if (PRODUCT_NAME == PRODUCT-1){ sh """ echo "Reached Here ${ENVIRONMENT} - ${PRODUCT_NAME} - ${SCM_BRANCH_NAME}" // do testing for product 1 """ } else{ stageResult = 'ABORTED' echo "PRODUCT not Available for Testing" } } } } stage('Testing-2'){ steps{ sh ''' echo "Reached Second Stage" ''' } } } } Any suggestions of how to implement the scenario that if conditions are not met set the stageResult as Abort, any suggestions either with a plugin or with a sample notation script is greatly appreciated Thanks
Below snippet worked for me. You can use catch error block and throw the error from that block when some condition met. You can also catch the exception in the post stage failure section. pipeline { agent { node { label 'master' } } environment{ ENVIRONMENT = "QA" PRODUCT_NAME = "PRODUCT-1" SCM_BRANCH_NAME = "master" } stages{ stage('Testing-1') { when{ expression{ ENVIRONMENT ==~ /(QA)/ } } steps { script { catchError(buildResult: 'FAILURE', stageResult: 'ABORTED'){ if (PRODUCT_NAME != PRODUCT-1) { error ("PRODUCT not Available for Testing") } sh """ echo "Reached Here ${ENVIRONMENT} - ${PRODUCT_NAME} - ${SCM_BRANCH_NAME}" // do testing for product 1 """ } } } post { failure { echo "Something Failed and error has been catched" } } } stage('Testing-2'){ steps{ sh ''' echo "Reached Second Stage" ''' } } }
How to skip a stage in Jenkinsfile pipeline when pipeline name ends with deliver?
I have 2 pipelines one for review and one for deploy. So when the pipeline ends with review, I want to skip Jenkinsfile execution. However, when it ends with deploy, it should execute the stage or the Jenkinsfile. I tried to use if, but this is a declarative pipeline, so when should be used. I want to avoid execution of stage using when condition if I encounter deploy pipeline end. #!/usr/bin/env groovy final boolean Deploy = (env.JOB_NAME as String).endsWith("-deploy") pipeline { agent any parameters { choice( choices: ['greeting' , 'silence'], description: '', name: 'REQUESTED_ACTION') } stages { //how to ouse when here to use deploy vairable to avoide execution of stage below stage ('Speak') { steps { echo "Hello, bitwiseman!" } } } }
You can skip stages in declarative pipelines using when, so the following should work. stages { stage('Deploy') { when { equals expected: true, actual: Deploy } steps { // ... } } }
An alternative to #StephenKing’s answer, which is also correct, you can rewrite the when block when evaluating Booleans as follows: stages { stage('Deploy') { when { expression { return Deploy } } steps { echo "Hello, bitwiseman!" // Step executes only when Deploy is true } } } This will execute the stage Deploy only when the variable Deploy evaluates to true, else the stage will be skipped.
I've got quite a hard time to find it too, but finally: stage('Speak') { when { expression { params.REQUESTED_ACTION != 'SILENCE' } } steps { echo "Hello, bitwiseman!" } } Jenkins docs with examples here: https://jenkins.io/doc/book/pipeline/syntax/#when-example
Here is an example for a Jenkins scripted pipeline: stage('Input of Scratch instance and Access token') { timeout(time: 60, unit: 'SECONDS') { script { try { env.SCRATCH_INSTANCE_URL = input message: 'Please enter the SCRATCH_INSTANCE_URL', parameters: [string(defaultValue: '', description: '', name: 'SCRATCH_INSTANCE_URL')] env.SCRATCH_ACCESS_TOKEN = input message: 'Please enter the SCRATCH_ACCESS_TOKEN', parameters: [string(defaultValue: '', description: '', name: 'SCRATCH_ACCESS_TOKEN')] } catch (Throwable e) { echo "Caught ${e.toString()}" currentBuild.result = "SUCCESS" } } } } // ------------------------------------------------------------------------- // Logout from Dev Hub. // ------------------------------------------------------------------------- stage('Logout from DevHub') { if (env.SCRATCH_INSTANCE_URL == null) { rc = command '''export SFDX_USE_GENERIC_UNIX_KEYCHAIN=true sfdx force:auth:logout --targetusername ${DEV_HUB_USERNAME} -p echo ${SCRATCH_INSTANCE_URL} echo ${SCRATCH_ACCESS_TOKEN} ''' } else { echo "Skipping this stage" } }
Even you can skip some parts of the steps using below code. Let's say REQUIRED_UPLOAD_INSTALL is a parameter. stage('Checking Mail List') { steps { script { if(!(env.REQUIRED_UPLOAD_INSTALL.toBoolean())) { env.mail_list = 'test#testg.com' } } } } But it doesn't support in post steps, not even in the when syntax.
post equivalent in scripted pipeline?
What is the syntax of 'post' in scripted pipeline comparing to declarative pipeline? https://jenkins.io/doc/book/pipeline/syntax/#post
For scripted pipeline, everything must be written programmatically and most of the work is done in the finally block: Jenkinsfile (Scripted Pipeline): node { try { stage('Test') { sh 'echo "Fail!"; exit 1' } echo 'This will run only if successful' } catch (e) { echo 'This will run only if failed' // Since we're catching the exception in order to report on it, // we need to re-throw it, to ensure that the build is marked as failed throw e } finally { def currentResult = currentBuild.result ?: 'SUCCESS' if (currentResult == 'UNSTABLE') { echo 'This will run only if the run was marked as unstable' } def previousResult = currentBuild.getPreviousBuild()?.result if (previousResult != null && previousResult != currentResult) { 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' } echo 'This will always run' } } https://jenkins.io/doc/pipeline/tour/running-multiple-steps/#finishing-up
You can modify #jf2010 solution so that it looks a little neater (in my opinion) try { pipeline() } catch (e) { postFailure(e) } finally { postAlways() } def pipeline(){ stage('Test') { sh 'echo "Fail!"; exit 1' } println 'This will run only if successful' } def postFailure(e) { println "Failed because of $e" println 'This will run only if failed' } def postAlways() { println 'This will always run' }