UFO ET IT

선언적 Jenkins 파이프 라인의 단계간에 변수를 어떻게 전달합니까?

ufoet 2020. 12. 1. 20:09
반응형

선언적 Jenkins 파이프 라인의 단계간에 변수를 어떻게 전달합니까?


선언적 파이프 라인의 단계간에 변수를 어떻게 전달합니까?

스크립팅 된 파이프 라인에서 절차는 임시 파일에 쓴 다음 파일을 변수로 읽는 것입니다.

선언적 파이프 라인에서 어떻게해야합니까?

예를 들어 셸 작업에 의해 생성 된 변수를 기반으로 다른 작업의 빌드를 트리거하고 싶습니다.

stage("stage 1") {
    steps {
        sh "do_something > var.txt"
        // I want to get var.txt into VAR
    }
}
stage("stage 2") {
    steps {
        build job: "job2", parameters[string(name: "var", value: "${VAR})]
    }
}

파일을 사용하려면 (스크립트가 필요한 값을 생성하기 때문에) readFile아래와 같이 사용할 수 있습니다. 그렇지 않은 경우 아래 sh표시된 script옵션과 함께 사용 하십시오 .

// Define a groovy global variable, myVar.
// A local, def myVar = 'initial_value', didn't work for me.
// Your mileage may vary.
// Defining the variable here maybe adds a bit of clarity,
// showing that it is intended to be used across multiple stages.
myVar = 'initial_value'

pipeline {
  agent { label 'docker' }
  stages {
    stage('one') {
      steps {
        echo "${myVar}" // prints 'initial_value'
        sh 'echo hotness > myfile.txt'
        script {
          // OPTION 1: set variable by reading from file.
          // FYI, trim removes leading and trailing whitespace from the string
          myVar = readFile('myfile.txt').trim()

          // OPTION 2: set variable by grabbing output from script
          myVar = sh(script: 'echo hotness', returnStdout: true).trim()
        }
        echo "${myVar}" // prints 'hotness'
      }
    }
    stage('two') {
      steps {
        echo "${myVar}" // prints 'hotness'
      }
    }
    // this stage is skipped due to the when expression, so nothing is printed
    stage('three') {
      when {
        expression { myVar != 'hotness' }
      }
      steps {
        echo "three: ${myVar}"
      }
    }
  }
}

간단히:

  pipeline {
        parameters {
            string(name: 'custom_var', defaultValue: '')
        }

        stage("make param global") {
             steps {
               tmp_param =  sh (script: 'most amazing shell command', returnStdout: true).trim()
               env.custom_var = tmp_param
              }
        }
        stage("test if param was saved") {
            steps {
              echo "${env.custom_var}"
            }
        }
  }

참고 URL : https://stackoverflow.com/questions/44099851/how-do-i-pass-variables-between-stages-in-a-declarative-jenkins-pipeline

반응형