MarEng
MarEng

Reputation: 308

Jenkins java.lang.NoSuchMethodError: No such DSL method 'post' found among steps

I'm trying to implement a stage on Jenkins to send email when a failure is produced on Jenkins. I made something similar to the Jenkins documention:

    #!/usr/bin/env groovy
    
    node {
    
    stage ('Send Email') {
            
            echo 'Send Email'
            
                post {
                    failure {
                        mail to: '[email protected]',
                             subject: "Failed Pipeline: ${currentBuild.fullDisplayName}",
                             body: "Something is wrong with ${env.BUILD_URL}"
                    }
                }
                        
            }
    
    }

But I always get this error:

java.lang.NoSuchMethodError: No such DSL method 'post' found among steps [archive, bat, build, catchError, checkout, deleteDir, dir, dockerFingerprintFrom, dockerFingerprintRun, echo, emailext, emailextrecipients, envVarsForTool, error, fileExists, getContext, git, input, isUnix, library, libraryResource, load, mail, milestone, node, parallel, powershell, properties, publishHTML, pwd, readFile, readTrusted, resolveScm, retry, script, sh, sleep, stage, stash, step, svn, timeout, timestamps, tm, tool, unarchive, unstash, validateDeclarativePipeline, waitUntil, withContext, withCredentials, withDockerContainer, withDockerRegistry, withDockerServer, withEnv, wrap, writeFile, ws] or symbols [all, allOf, always, ant, antFromApache, antOutcome, antTarget, any, anyOf, apiToken, architecture, archiveArtifacts, artifactManager, authorizationMatrix, batchFile, booleanParam, branch, buildButton, buildDiscarder, caseInsensitive, caseSensitive, certificate, changelog, changeset, choice, choiceParam, cleanWs, clock, cloud, command, credentials, cron, crumb, defaultView, demand, disableConcurrentBuilds, docker, dockerCert, dockerfile, downloadSettings, downstream, dumb, envVars, environment, expression, file, fileParam, filePath, fingerprint, frameOptions, freeStyle, freeStyleJob, fromScm, fromSource, git, github, githubPush, gradle, headRegexFilter, headWildcardFilter, hyperlink, hyperlinkToModels, inheriting, inheritingGlobal, installSource, jacoco, jdk, jdkInstaller, jgit, jgitapache, jnlp, jobName, junit, label, lastDuration, lastFailure, lastGrantedAuthorities, lastStable, lastSuccess, legacy, legacySCM, list, local, location, logRotator, loggedInUsersCanDoAnything, masterBuild, maven, maven3Mojos, mavenErrors, mavenMojos, mavenWarnings, modernSCM, myView, node, nodeProperties, nonInheriting, nonStoredPasswordParam, none, not, overrideIndexTriggers, paneStatus, parameters, password, pattern, pipeline-model, pipelineTriggers, plainText, plugin, pollSCM, projectNamingStrategy, proxy, queueItemAuthenticator, quietPeriod, remotingCLI, run, runParam, schedule, scmRetryCount, search, security, shell, skipDefaultCheckout, skipStagesAfterUnstable, slave, sourceRegexFilter, sourceWildcardFilter, sshUserPrivateKey, stackTrace, standard, status, string, stringParam, swapSpace, text, textParam, tmpSpace, toolLocation, unsecured, upstream, usernameColonPassword, usernamePassword, viewsTabBar, weather, withAnt, zfs, zip] or globals [currentBuild, docker, env, params, pipeline, scm]

I saw some others post, but the suggestion made did not work for me

Upvotes: 20

Views: 48945

Answers (3)

vishnuudayan
vishnuudayan

Reputation: 19

The following snippet worked for me in a scripted pipeline. I have added a new stage to my existing ones.

stage ('Send Email') {
        echo "Mail Stage";

         mail to: "[email protected]",
         cc: '[email protected]', charset: 'UTF-8', 
         from: '[email protected]', mimeType: 'text/html', replyTo: '', 
         bcc: '',
         subject: "CI: Project name -> ${env.JOB_NAME}",
         body: "<b>Example</b><br>Project: ${env.JOB_NAME} <br>Build Number: ${env.BUILD_NUMBER} <br> URL de build: ${env.BUILD_URL}";
    }

Upvotes: 0

Andrius Butkus
Andrius Butkus

Reputation: 99

Problem you are having is that you node is not added to declarative pipeline, you can't use post on node. You need to wrap your node with declarative pipeline.

Here is example code

pipeline {
    agent any
    stages {
        stage('Send Email') {
            steps {
            node ('master'){
                echo 'Send Email'
            }
        }
        }
    }
    post { 
        always { 
            echo 'I will always say Hello!'
        }
        aborted {
            echo 'I was aborted'
        }
        failure {
            mail to: '[email protected]',
            subject: "Failed Pipeline: ${currentBuild.fullDisplayName}",
            body: "Something is wrong with ${env.BUILD_URL}"
        }
    }
}

Upvotes: 9

Caio Dornelles Antunes
Caio Dornelles Antunes

Reputation: 378

I was having the same problem here. Lots of examples for declarative... none for scripted. It almost leads you to believe that there is no solution, but that wouldn't make sense.

This worked for me (it works without the try/finally -- or catch if you want).

node {
    //some var declarations... or whatever

    try {
        //do some stuff, run your tests, etc.            
    } finally {
        junit 'build/test-results/test/*.xml'
    }
}

*EDIT: take a look at their documentation... accidentally I've done exactly what they recommend. Just click on the "Toggle Scripted Pipeline (Advanced)" link and you'll see it.

Upvotes: 23

Related Questions