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

emailJenkins

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: 'aa@bb.cc',
                             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

Best Answer

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.