首页 > 解决方案 > 如何在cps脚本jenkins中获取变量?

问题描述

我有 .yaml 文件,其中包含以下变量(请注意这是一个片段),我在其中调用 CPS 脚本中的变量。当我在 Jenkins 上运行它时,出现以下错误:

java.lang.NullPointerException:无法在空对象上调用方法startsWith()

请注意,当我调用 _agent_label 时,它能够解析它,而 env._branch_name 返回“null”。如何在我的 CPS groovy 脚本之外调用变量?

apiVersion: v1
data:
  jobs.yaml: |-
    jobs:
      - script: |
.
.
.
.
.

_agent_label = flex_job.get('agent_label', 'agent')
workspace_dir = flex_job.get('jenkins_pipeline')
jenkinsfile = 'Jenkinsfile'
_branch_name = flex_job.get('branch_name', 'refs/heads/master')

再往下,我有以下 Jenkins Groovy CPS 代码

definition {
  cps {
    script("""

      * Prepare branch reference and name.
      */
      def branch_ref() {
          echo "---------------- Prepare variable names ----------------"
          regex_prefix = ~"^refs/heads/"
          echo env.branch_name <----- returns nulls
          echo "Before the if "
          if (env._branch_name.startsWith('refs/')) {
              echo "Inside the if statement"
              remote_branch_ref = env._branch_name
              echo "Remote Branch Ref: $remote_branch_ref"
          } else {
              echo "inside the else statement"
              remote_branch_ref = 'refs/heads/' + env._branch_name
              echo "Remote Branch Ref: $remote_branch_ref"
          }
          echo "otherwise something else"
          // For example refs/heads/master - refs/heads/ -> master
          local_branch_name = env._branch_name - env.regex_prefix
          echo "Local branch name: $local_branch_name"
      }
      node(env._agent_label) {
          stage("Git scripted scm") {
              echo "monkey"
              branch_ref()
          }
      }
    """.stripIndent())
  }
}

标签: jenkinsgroovyjenkins-pipelinejenkins-groovy

解决方案


推荐阅读