Jenkins 管道在处理 json 文件时出错

Jenkins pipeline error in handling json file

我是 Jenkins 管道的新手,正在编写 groovy 脚本来解析 json 文件。但是,我遇到了很多人都遇到过的错误,但是 none 的解决方案对我有用。下面是我的 Jenkinsfile 和错误消息。

def envname = readJSON file: '${env.WORKSPACE}/manifest.json'
pipeline {
    agent any
    stages { 
        stage('Build') {
            steps {
                echo WORKSPACE
                sh "ls -a ${WORKSPACE}"
            } 
        }
        }
 }

[Pipeline] Start of Pipeline [Pipeline] readJSON [Pipeline] End of Pipeline org.jenkinsci.plugins.workflow.steps.MissingContextVariableException: Required context class hudson.FilePath is missing Perhaps you forgot to surround the code with a step that provides this, such as: node at org.jenkinsci.plugins.pipeline.utility.steps.AbstractFileOrTextStepExecution.run(AbstractFileOrTextStepExecution.java:30)

我什至尝试了 readJSON file: '${WORKSPACE}/manifest.json,但那也没用。我确定错误出在第一行,因为删除该行时,执行成功。这些文档非常有用,但我无法找出我到底哪里出错了,这就是为什么要在这里发布的原因。

更新:

我尝试了以下方法 def envname = readJSON file: "./manifest.json"def envname = readJSON file: "${env.WORKSPACE}/manifest.json",甚至尝试在 steps 块下定义它们。没有任何效果。以下是我在步骤块

下定义它们时收到的错误消息

WorkflowScript: 5: Expected a step @ line 7, column 13 def envname = ^

下面是readJson的官方语法文档,我可以看到我只使用了正确的语法。但仍然没有按预期工作。 https://www.jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#readjson-read-json-from-files-in-the-workspace

'${env.WORKSPACE}/manifest.json' 将 Groovy env 映射作为 shell 变量进行插值。您需要将其插入为 Groovy 变量,例如 "${env.WORKSPACE}/manifest.json".

sh "ls -a ${WORKSPACE}" 将 shell 环境变量 WORKSPACE 插入为 Groovy 变量。您需要将其插入为 shell 变量,例如 sh 'ls -a ${WORKSPACE}'.

echo WORKSPACE 正在尝试将 shell 变量 WORKSPACE 解析为第一个 class Groovy 变量表达式。您需要使用 Groovy env 映射而不是 echo env.WORKSPACE.

关于第一行的全局变量不确定类型赋值:如果在进行这些修复后仍然抛出上述错误,则可能是由于在声明性语法管道中使用脚本语法无效。在这种情况下,您可能需要将它放在管道中的 step 块中。

在“Matt Schuchard”的以下回答的帮助下,我自己解决了这个问题。我不确定这是否是解决问题的唯一方法,但这对我有用。

pipeline {
    agent any
    stages { 
        stage('Json-Build') {
            steps {
                script {
                    def envname = readJSON file: "${env.WORKSPACE}/manifest.json"
                    element1 = "${envname.dev}"
                    echo element1
                }
            } 
        }
        }
 }