宣言型 Jenkins パイプラインのステージ間で変数を渡すにはどうすればいいですか? 質問する

宣言型 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})]
    }
}

ベストアンサー1

ファイルを使用する場合は (必要な値を生成するのはスクリプトであるため)、readFile以下のように使用できます。そうでない場合は、以下のようにオプションshを使用します。script

// Define a groovy local variable, myVar.
// A global variable without the def, like myVar = 'initial_value',
// was required for me in older versions of jenkins. 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.
def myVar = 'initial_value'

pipeline {
  agent { label 'docker' }
  stages {
    stage('one') {
      steps {
        echo "1.1. ${myVar}" // prints '1.1. 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()
        }
        echo "1.2. ${myVar}" // prints '1.2. hotness'
      }
    }
    stage('two') {
      steps {
        echo "2.1 ${myVar}" // prints '2.1. hotness'
        sh "echo 2.2. sh ${myVar}, Sergio" // prints '2.2. sh hotness, Sergio'
      }
    }
    // this stage is skipped due to the when expression, so nothing is printed
    stage('three') {
      when {
        expression { myVar != 'hotness' }
      }
      steps {
        echo "three: ${myVar}"
      }
    }
  }
}

おすすめ記事