需要上下文类 hudson.FilePath,但缺失了。也许您忘记在代码周围添加提供此类的步骤,例如:node。

22

当我在Jenkinsfile中加载另一个Groovy文件时,它会显示以下错误。

"需要上下文类hudson.FilePath不存在 也许您忘记将代码用提供此类的步骤括起来,例如:node"

我创建了一个包含函数的Groovy文件,并希望在我的Declarative Jenkinsfile中调用它。但是它显示出错。

My Jenkinsfile--->

def myfun = load 'testfun.groovy'
pipeline{
    agent any
    environment{
        REPO_PATH='/home/manish/Desktop'
        APP_NAME='test'
    }
    stages{
        stage('calling function'){
            steps{
                script{
                    myfun('${REPO_PATH}','${APP_NAME}')
                }
             }
         }
     }
  }

结果--

org.jenkinsci.plugins.workflow.steps.MissingContextVariableException:需要上下文类hudson.FilePath,但缺少 也许您忘记用提供此内容的步骤将代码包围起来,例如:node

建议我该怎么做。

5个回答

6

你需要使用一个脚本流水线,并将"load"指令放在节点部分内(参见这个问题),或者如果你已经在使用声明式流水线(似乎是这种情况),你可以将它包含在"environment"部分中:

environment {
    REPO_PATH='/home/manish/Desktop'
    APP_NAME='test'
    MY_FUN = load 'testfun.groovy'
}

2

我在管道内的初始脚本块中加载函数成功了。就像下面这样:

def myfun

pipeline {
    agent any
    environment {
        REPO_PATH='/home/manish/Desktop'
        APP_NAME='test'
    }
    stages {
        stage('load function') {
            steps {
                script {
                    myfun = load 'testfun.groovy'
                }
            }
        }
        stage('calling function') {
            steps {
                script {
                    myfun("${REPO_PATH}","${APP_NAME}")
                }
            }
        }
    }
}

2

我们需要使用node {}进行包装,这样jenkins执行器才能在节点上执行。如果我们想要在特定代理节点上执行,则可以像node('代理名称'){}一样进行说明。

示例:

node {

def myfun = load 'testfun.groovy'
pipeline{
    agent any
    environment{
        REPO_PATH='/home/manish/Desktop'
        APP_NAME='test'
    }
    stages{
        stage('calling function'){
            steps{
                script{
                    myfun('${REPO_PATH}','${APP_NAME}')
                }
             }
         }
     }
  }

}

4
这似乎不起作用,Jenkins抱怨pipeline不在顶层。 - gastrodon
将环境声明移至舞台内部。 - Ayeshmantha Perera
1
pipeline 应该在声明式语法中位于顶部。 - rolandsaven

2
另一个可能性是由于早期/潜在的错误,上下文已被删除,例如由多个执行器机器。如果您缺少节点(例如脚本)-块,但尤其是在后置 always -块中,就会发生这种情况。您还可以在其他地方使用 if -检查。在此之后,您将获得另一个错误,导致出现此错误消息。
post {
  always {
    script {
       //skip the step if context is missing
       if (getContext(hudson.FilePath)) {
         echo "It works"
       }
     }
   }
 }

请查看https://docs.cloudbees.com/docs/cloudbees-ci-kb/latest/troubleshooting-guides/how-to-troubleshoot-hudson-filepath-is-missing-in-pipeline-run



1
当我调用一个在仓库/文件系统中不存在的sh脚本时,我收到了这个错误消息。请查看堆栈跟踪中的以下行:
at WorkflowScript.run(WorkflowScript:135)

135 行标记了 Jenkinsfile 中发生错误或缺少脚本的位置。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接