Groovy:看起来像是一个范围问题,但找不到位置,可以吗?

时间:2017-06-11 12:29:21

标签: groovy jenkins-pipeline

我写了一些函数来帮助我编写Jenkins管道。

以下函数负责返回shell命令输出:

def gen_uuid(){
    randomUUID() as String
}

def sh_out(cmd){
    String uuid = gen_uuid()
    sh """( ${cmd} )> ${uuid}"""
    String out = readFile(uuid).trim()
    sh "set +x ; rm ${uuid}"
    return out
}

如图所示,这是另一个功能:

Map get_started_by(){
  withCredentials([ // Use Jenkins credentials ID of artifactory
      [$class: 'UsernamePasswordMultiBinding', credentialsId: '0b8d591a-f4ce-XXXX-XXXX-faecb504d3d0', usernameVariable: 'J_USER', passwordVariable: 'J_PASS'],
  ]){
    List startedBy = sh_out("""
        set +x; curl -u ${J_USER}:${J_PASS} '${env.BUILD_URL}api/json' 2>/dev/null | \
        python -mjson.tool | \
        awk -F'"' '/(userId|userName)/{print \$4}'
    """).split(/(\n)/)
    return [
        userId: startedBy[0],
        userName: startedBy[1]
    ]
  }
}

返回发出作业的用户的userId和userName。

然后,我的问题在于这个功能:

def run_in_stage_func(String stage_name, Closure command, String sendTo){

  String started_by = get_started_by()
  String ulink = "<@${started_by['userId']}>"
  String jlink = "(<${env.BUILD_URL}|Open>)"

  println "============================================================"
  stage (stage_name) {
      try {
          command()
          if (currentBuild.result == 'FAILURE') {
              error "Build failed, see log for further details."
          }
          println "============================================================"
      } catch (Exception ex) {
          def except = "${ex}"
          slackSend channel: channel, color: 'danger', teamDomain: null, token: null,
              message: " :${ulink} *Failed to build ${env.JOB_NAME}*! :x: ${jlink} (<!here|here>)"
          echo "Pipeline failed at stage: ${stage_name}"
          throw ex
      }
  }
}

当我运行作业时,我收到以下错误:

groovy.lang.MissingPropertyException: No such property: userId for class: java.lang.String

“String ulink =”&lt; @ $ {started_by ['userId']}&gt;“这一行可能是什么原因?” ' - 没有按预期工作?

1 个答案:

答案 0 :(得分:1)

您明确地将get_started_by()的结果投射到String。要解决此问题,请将代码更改为

def started_by = get_started_by() 

Map started_by = get_started_by()