当前位置: 首页 > 知识库问答 >
问题:

Jenkinsfile加载groovy脚本的几个问题

傅英喆
2023-03-14

我想将一些常见的阶段移动到groovy文件中,以便其他Jenkinsfile可以使用这些阶段而不必复制它们。

我遇到了一些管道很好地加载groovy文件的问题,但当它使用groovy文件中的函数时,会弹出异常。

    java.lang.NoSuchMethodError: No such DSL method 'setup_cd' found among steps [VersionNumber, addEmbeddableBadgeConfiguration, archive, bat, browserStackReportPublisher, browserstack, browserstackAppUploader, build, catchError, checkout, deleteDir, dir, dockerFingerprintFrom, dockerFingerprintRun, dockerNode, echo, emailext, emailextrecipients, envVarsForTool, error, fileExists, findBuildScans, getContext, git, input, isUnix, junit, library, libraryResource, load, lock, mail, milestone, node, parallel, powershell, properties, pwd, pwsh, readFile, readTrusted, resolveScm, retry, script, sh, sleep, sshagent, stage, stash, step, timeout, timestamps, tm, tool, unarchive, unstable, unstash, validateDeclarativePipeline, waitUntil, warnError, withContext, withCredentials, withDockerContainer, withDockerRegistry, withDockerServer, withEnv, withGradle, wrap, writeFile, ws] or symbols [all, allOf, always, ant, antFromApache, antOutcome, antTarget, any, anyOf, apiToken, architecture, archiveArtifacts, artifactManager, attach, authorizationMatrix, batchFile, booleanParam, branch, brokenBuildSuspects, brokenTestsSuspects, buildButton, buildDiscarder, buildDiscarders, buildingTag, caseInsensitive, caseSensitive, certificate, changeRequest, changelog, changeset, checkoutToSubdirectory, choice, choiceParam, cleanWs, clock, command, credentials, cron, crumb, culprits, defaultFolderConfiguration, defaultView, demand, developers, devicefarm, disableConcurrentBuilds, disableResume, docker, dockerCert, dockerfile, downstream, dumb, durabilityHint, envVars, envVarsFilter, environment, equals, expression, file, fileParam, filePath, fingerprint, fingerprints, frameOptions, freeStyle, freeStyleJob, fromScm, fromSource, git, gitBranchDiscovery, gitHubBranchDiscovery, gitHubBranchHeadAuthority, gitHubExcludeArchivedRepositories, gitHubForkDiscovery, gitHubPullRequestDiscovery, gitHubSshCheckout, gitHubTagDiscovery, gitHubTrustContributors, gitHubTrustEveryone, gitHubTrustNobody, gitHubTrustPermissions, gitTagDiscovery, github, githubPush, gradle, headRegexFilter, headWildcardFilter, hyperlink, hyperlinkToModels, inheriting, inheritingGlobal, installSource, isRestartedRun, jdk, jdkInstaller, jgit, jgitapache, jnlp, jobBuildDiscarder, jobName, label, lastDuration, lastFailure, lastGrantedAuthorities, lastStable, lastSuccess, legacy, legacySCM, list, local, location, logRotator, loggedInUsersCanDoAnything, mailer, masterBuild, maven, maven3Mojos, mavenErrors, mavenGlobalConfig, mavenMojos, mavenWarnings, modernSCM, myView, newContainerPerStage, node, nodeProperties, nonInheriting, none, not, overrideIndexTriggers, paneStatus, parallelsAlwaysFailFast, parameters, password, pattern, permanent, pipeline-model, pipeline-model-docker, pipelineTriggers, plainText, plugin, pollSCM, preserveStashes, projectNamingStrategy, proxy, queueItemAuthenticator, quietPeriod, rateLimitBuilds, recipients, requestor, resourceRoot, retainOnlyVariables, run, runParam, sSHLauncher, schedule, scmRetryCount, scriptApproval, scriptApprovalLink, search, security, shell, simpleBuildDiscarder, skipDefaultCheckout, skipStagesAfterUnstable, slave, sourceRegexFilter, sourceWildcardFilter, ssh, sshPublicKey, sshUserPrivateKey, standard, status, string, stringParam, swapSpace, tag, teamSlugFilter, text, textParam, timezone, tmpSpace, toolLocation, triggeredBy, unsecured, upstream, upstreamDevelopers, userSeed, usernameColonPassword, usernamePassword, viewsTabBar, weather, withAnt, zip] or globals [currentBuild, docker, env, params, pipeline, scm]
    at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:202)
    at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:122)
    at sun.reflect.GeneratedMethodAccessor583.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1213)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:42)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:163)
    at org.kohsuke.groovy.sandbox.GroovyInterceptor.onMethodCall(GroovyInterceptor.java:23)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:157)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:142)
    at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:161)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:165)
    at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:17)
    at WorkflowScript.run(WorkflowScript:45)
    at ___cps.transform___(Native Method)
    at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:86)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:113)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:83)
    at sun.reflect.GeneratedMethodAccessor154.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.LocalVariableBlock$LocalVariable.get(LocalVariableBlock.java:39)
    at com.cloudbees.groovy.cps.LValueBlock$GetAdapter.receive(LValueBlock.java:30)
    at com.cloudbees.groovy.cps.impl.LocalVariableBlock.evalLValue(LocalVariableBlock.java:28)
    at com.cloudbees.groovy.cps.LValueBlock$BlockImpl.eval(LValueBlock.java:55)
    at com.cloudbees.groovy.cps.LValueBlock.eval(LValueBlock.java:16)
    at com.cloudbees.groovy.cps.Next.step(Next.java:83)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:174)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:163)
    at org.codehaus.groovy.runtime.GroovyCategorySupport$ThreadCategoryInfo.use(GroovyCategorySupport.java:129)
    at org.codehaus.groovy.runtime.GroovyCategorySupport.use(GroovyCategorySupport.java:268)
    at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:163)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:18)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:51)
    at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:185)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:400)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$400(CpsThreadGroup.java:96)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:312)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:276)
    at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:67)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:139)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at jenkins.security.ImpersonatingExecutorService$1.run(ImpersonatingExecutorService.java:68)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Finished: FAILURE

这是示例代码,我在jenkins配置中使用管道脚本,而不是在SCM的Jenkinsfile中使用。

# Jenkinsfile

def DOCKER_HOST = 'beta-vpc'
def REGION = 'FRANKFURT'
def STAGE = 'BETA'
def CD_PROJ = "test"
def DOCKER_HOST_IP=''
def DOCKER_HOST_PORT='80'
node(DOCKER_HOST) {
    def HAS_DB_MIGRATION = 'no'
    
    stage("Checkout") {
        DOCKER_HOST_IP = sh (
            script: 'ip route get 8.8.8.8 | awk \'{print $NF; exit}\'',
            returnStdout: true
        ).trim()
        echo "Running on ${NODE_NAME}: ${DOCKER_HOST_IP}"
        echo "Clean workspace"
        sh "rm -rf *"
    
        echo "Checkout ${CD_PROJ}"
        // checkout([$class: 'GitSCM', branches: [[name: '*/master']], doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'CleanCheckout'], [$class: 'RelativeTargetDirectory', relativeTargetDir: "${CD_PROJ}"], [$class: 'CleanBeforeCheckout']], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'token', url: "https://our.github.com/PROJECT/${CD_PROJ}.git"]]])
        sh "ls -alh"

        COMMON_LIBRARY = load "${CD_PROJ}/common.groovy"
    }
    
    docker.image('centos:6').inside("-u 0:0 -e ANSIBLE_HOST_KEY_CHECKING=False -p ${DOCKER_HOST_PORT}:${DOCKER_HOST_PORT}") {
        stage('Setup CD env') {
            (LATEST_BUILD_NUMBER, BRANCH) = COMMON_LIBRARY.setup_cd(CD_PROJ, CONFIG_PROJ)
            try {
                (LATEST_BUILD_NUMBER, BRANCH) = COMMON_LIBRARY.setup_cd(CD_PROJ, CONFIG_PROJ)
            } 
            catch(Exception e) {
                COMMON_LIBRARY.failSendMail(EMAIL_TO, e)
            }
        }
    }
}

和groovy文件。

# test/common.groovy
String[] setup_cd(cd_proj, config_proj, region, stage) {
    if (stage == 'BETA') {
        s = 'beta'
    }

    sh "./${cd_proj}/setup_cd.sh ./${cd_proj} ./${config_proj} ${region.toLowerCase()} ${s}"
    latest_build_number = sh (
        script: "rpm -qa | grep -e \"something_*\" | tail -n 1 | cut -d '-' -f 2,3 | cut -d '.' -f 1,2,3,4,5",
        returnStdout: true
    ).trim()
    if (latest_build_number.contains('master')) {
        branch = 'master'
    } else if (latest_build_number.contains('pr')) {
        tmp = latest_build_number.tokenize('.').last()
        // concat to PR-XXXX
        branch = tmp[1..2].toUpperCase() + '-' + tmp[3..-1]
    }
    currentBuild.setDisplayName("${latest_build_number}")
    return [latest_build_number, branch]
}
return this

共有1个答案

梁嘉澍
2023-03-14

好的,我找到解决方案了。因为我不熟悉Java,我忘了虽然方法签名的数量和你定义的不一样,但它们不是同一个函数。

 类似资料:
  • 目前,我有一个“包罗万象”的jenkinsfile,其中包含各种函数。为了在其他jenkinsfile中重用这些函数,我想将它们放在单独的groovy脚本中,并从jenkinsfile中加载它们。 scmHandler。groovy: 在jenkinsfile中,我执行以下操作: <代码>。。。def scmHandler=负载(“测试/scmHandler.groovy”)scmHandler。

  • 我正在使用gradle和bash脚本在docker图像中构建几个android应用程序。该脚本由运行docker映像的jenkins触发。在bash脚本中,我收集有关构建成功的信息。我想将该信息传递给jenkinsfile的groovy脚本。我试图在docker容器中创建一个txt文件,但jenkinsfile中的groovy脚本找不到该文件。这是我的jenkinsfile的groovy脚本: 在

  • 我正在Activiti中加载一个具有以下结构的Groovy项目: 剧本groovy公司 傅。groovy公司 我的问题是我的脚本的导入语句:没有被Activiti解决。 我正在Spring容器中使用org运行Activiti。activiti:activiti spring:5.21.0。我的脚本使用org中的groovy脚本引擎进行评估。activiti引擎:5.21.0。 如何让Activit

  • 我有一个jenkins管道,它加载如下groovy实用程序脚本: 当我在主节点上执行管道时,一切都很好。在这种情况下,我可以在管道中使用类Utils中的方法。 当我试图在一个从系统中执行管道时,我的问题出现了。在这种情况下,上述负载会导致错误 Java语言io。IOException:java。io。FileNotFoundException:/var/lib/jenkins/utils/util

  • 问题内容: 在我的jenkins管道文件中,我使用从.json文件读取构建配置。但是,这引入了需要 在进程内“脚本批准” 页面上批准的代码。通过GUI执行此操作时,效果很好。 但是,我还有一个脚本会自动设置我的jenkins机器,该机器将创建不需要任何GUI操作即可使用的现成机器。该脚本已使用jenkins脚本控制台批准从属启动命令。在脚本控制台中执行此操作的常规代码如下所示。 效果很好,但现在我

  • 问题内容: 我想从CDN加载脚本,然后在React中执行该脚本公开的功能: 该脚本有时需要花费一些时间(通常是第一次)加载,并且何时调用“ foo”不可用,并且出现如下错误: TypeError:无法读取未定义的属性“ render” 如何确保脚本成功加载后调用? 问题答案: 根据React Component Specs和Lifecycle的说法,我认为在componentWillMount()