You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jenkins Pipeline中withCredentials块语法错误排查求助

Jenkins Pipeline withCredentials 语法错误修复方案

问题概述

在Jenkins声明式Pipeline中使用withCredentials时出现语法错误,无论调整其位置都无法解决,报错提示stage块内只能包含steps、stages或parallel。

原代码

pipeline {
    agent {
        node {
            label 'node1'
        }
    }
    stages {
        stage('saving stross token and printing') {
            withCredentials([string(credentialsId: 'devadrita-stross', variable: 'deva-stross')]) {
                steps {
                    script {
                        bat """
                        python -u C://Users//Administrator//Desktop//stross//stross-script.py, token = "${deva-stross}"
                        """
                    }
                }
            }
        }
    }
}

报错信息

Started by user admin
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 8: Unknown stage section "withCredentials". Starting with version 0.5, steps in a stage must be in a ‘steps’ block. @ line 8, column 9.
           stage('saving stross token and printing') {
           ^

WorkflowScript: 8: Expected one of "steps", "stages", or "parallel" for stage "saving stross token and printing" @ line 8, column 9.
           stage('saving stross token and printing') {
           ^

错误原因

声明式Pipeline对stage的结构有严格要求:stage的直接子元素只能是steps、stages或parallel,withCredentials属于步骤(step),必须放在steps块内部,不能直接作为stage的子元素。

修复后的代码

pipeline {
    agent {
        node {
            label 'node1'
        }
    }
    stages {
        stage('saving stross token and printing') {
            steps {
                withCredentials([string(credentialsId: 'devadrita-stross', variable: 'deva-stross')]) {
                    script {
                        bat """
                        python -u C://Users//Administrator//Desktop//stross//stross-script.py token="${deva-stross}"
                        """
                    }
                }
            }
        }
    }
}

额外调整说明

  • 移除了bat命令中Python脚本路径后的逗号,改为空格,确保参数传递格式正确。
  • 将withCredentials嵌套到steps内部,符合声明式Pipeline的语法规范。

内容的提问来源于stack exchange,提问作者Devadrita Bose

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 04:10:41