如何在Jenkins管道中操纵变量

时间:2019-02-21 01:55:21

标签: sed jenkins-pipeline

尝试几次尝试和错误,以了解在何处或如何在变量中剪切字符串并将其分配给jenkins stage使用的新变量。通常,只需删除以下指示的 -TEST Jenkins管道即可:

properties([
    [$class: 'RebuildSettings', autoRebuild: false, rebuildDisabled: false], 
    parameters([choice(choices: ['SQA-ENV-CLONE', 'DEV-ENV-CLONE'], 
                description: 'Select the ENV', name: 'ENV')])])

pipeline {
  agent any

  stages {

    stage('VALIDATE ENVIRONMENT') {
      def ACTIVE = sh(returnStdout: true, script: "echo $ENV | sed -e 's/-CLONE//g'")

      steps {
         echo 'Checking 1st the ${ACTIVE}'
      }
    }
  }    
}   

我遇到错误

Running in Durability level: MAX_SURVIVABILITY
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 6: Not a valid stage section definition: "def ACTIVE = sh(returnStdout: true, script: "echo $ENV | sed -e 's/-CLONE//g'")". Some extra configuration is required. @ line 6, column 9.
       stage('VALIDATE ENVIRONMENT') {
       ^

1 error

at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1085)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:603)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:131)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:125)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:560)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:521)
at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:330)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:429)
Finished: FAILURE

假设我选择“ DEV-ENV-CLONE”作为我期望通过此输出成功构建的值:

Checking 1st the DEV-ENV

1 个答案:

答案 0 :(得分:0)

您需要将def ACTIVE = sh(...)移至管道步骤script,它们是Groovy脚本,只能由script步骤包装。

stage('VALIDATE ENVIRONMENT') {

  steps {

    script {
      ACTIVE = sh(
        returnStdout: true, 
        script: "echo $ENV | sed -e 's/-CLONE//g'"
      ).trim()      
    }

    echo "Checking 1st the ${ACTIVE}"
  }

}