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

Jenkinsfile中Groovy脚本报错:MissingPropertyException(gitUser未定义)

问题描述

在Jenkinsfile中编写流水线代码时,用于生成分支选择参数的Groovy脚本在Jenkins脚本控制台可正常运行,但在Jenkinsfile中执行时抛出以下错误:

groovy.lang.MissingPropertyException: No such property: gitUser for class: groovy.lang.Binding

尝试过声明gitUser和gitPass变量,也试过改用$(gitUser)语法,但问题仍未解决。

原代码片段

[$class: 'ChoiceParameter',
      choiceType: 'PT_SINGLE_SELECT',
      description: 'Select the BRANCH from the Dropdown List', 
      filterLength: 1, 
      filterable: false, 
      name: 'BRANCH',
      script: [$class: 'GroovyScript', 
        fallbackScript: [
            classpath: [], 
            sandbox: false, 
            script: 
                "return['Could not get The environemnts']"
        ],
        script: [
            classpath: [], 
            sandbox: false, 
            script: """ 
              import jenkins.*
              import jenkins.model.* 
              import hudson.*
              import hudson.model.*
                
                def jenkinsCredentials = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials( com.cloudbees.plugins.credentials.Credentials.class, Jenkins.instance, null, null )
                    
                    for (creds in jenkinsCredentials) {
                    if(creds.id == "gitJenkins") {
                        gitUser = creds.username
                        gitPass = creds.password
                         }
                    }

                def proc = "git ls-remote -h https://${gitUser}:${gitPass}@gitlab.innochain.ru/innochain/backoffice.git".execute()
                return proc.text.readLines().collect {it.split()[1].replaceAll('refs/heads/', '')}

            """
        ]
      ]
    ]
 ])
])            

报错堆栈

Also:   org.jenkinsci.plugins.workflow.actions.ErrorAction$ErrorId: 4f0d1584-9bcb-45cf-8f49-f16c82dd9511
groovy.lang.MissingPropertyException: No such property: gitUser for class: groovy.lang.Binding
    at groovy.lang.Binding.getVariable(Binding.java:63)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:285)
    at org.kohsuke.groovy.sandbox.impl.Checker$7.call(Checker.java:375)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:379)
    at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:29)
    at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20)
    at WorkflowScript.run(WorkflowScript:35)
    at ___cps.transform___(Native Method)
    at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.get(PropertyishBlock.java:73)
    at com.cloudbees.groovy.cps.LValueBlock$GetAdapter.receive(LValueBlock.java:30)
解决方法

问题根源在于Jenkins流水线的CPS沙箱环境中,未显式声明的变量会被尝试从全局Binding上下文获取,而非作为脚本局部变量处理。脚本控制台是全局执行环境,因此不会触发这个问题,但Jenkinsfile中的脚本受沙箱限制,必须显式声明局部变量。

具体修复步骤:

  • 显式声明局部变量:在脚本开头定义gitUser和gitPass,避免变量被绑定到全局Binding
  • 优化凭证查找逻辑:使用find方法替代循环,更简洁高效
  • 添加空值校验:防止凭证未找到时后续代码报错
  • 处理密码的明文转换:Jenkins凭证的密码是Secret类型,需要调用getPlainText()获取明文
修正后的代码
[$class: 'ChoiceParameter',
      choiceType: 'PT_SINGLE_SELECT',
      description: 'Select the BRANCH from the Dropdown List', 
      filterLength: 1, 
      filterable: false, 
      name: 'BRANCH',
      script: [$class: 'GroovyScript', 
        fallbackScript: [
            classpath: [], 
            sandbox: false, 
            script: "return ['Could not get the environments']"
        ],
        script: [
            classpath: [], 
            sandbox: false, 
            script: """ 
              import jenkins.*
              import jenkins.model.* 
              import hudson.*
              import hudson.model.*
              import com.cloudbees.plugins.credentials.Credentials
              import com.cloudbees.plugins.credentials.CredentialsProvider
                
              // 显式声明局部变量
              def gitUser = null
              def gitPass = null

              // 查找指定ID的凭证
              def gitCreds = CredentialsProvider.lookupCredentials(
                  Credentials.class, 
                  Jenkins.instance, 
                  null, 
                  null
              ).find { it.id == "gitJenkins" }

              if (gitCreds) {
                  gitUser = gitCreds.username
                  // 转换Secret类型的密码为明文
                  gitPass = gitCreds.password.getPlainText()
              }

              // 校验凭证是否获取成功
              if (!gitUser || !gitPass) {
                  return ["Failed to retrieve Git credentials"]
              }

              def proc = "git ls-remote -h https://${gitUser}:${gitPass}@gitlab.innochain.ru/innochain/backoffice.git".execute()
              return proc.text.readLines().collect { it.split()[1].replaceAll('refs/heads/', '') }

            """
        ]
      ]
    ]
 ])
])            

内容的提问来源于stack exchange,提问作者Dmitry Grechin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 03:30:33