简体   繁体   English

如何将变量从管道传递到 Jenkins 中的作业?

[英]How to pass variable from pipeline to job in Jenkins?

I need to create a unique identifier in a pipeline and then all jobs started from this pipeline should have access to this unique identifier.我需要在管道中创建一个唯一标识符,然后从此管道启动的所有作业都应该可以访问这个唯一标识符。
I do not want to parameterize those jobs.我不想参数化这些工作。

I thought that environment variable defined on a pipeline level will be accessible from jobs, but it isn't.我认为在管道级别上定义的环境变量可以从作业中访问,但事实并非如此。

pipeline {
   agent any
   environment {
       TEST_VAR = 'TEST_VAR'
   }
   stages {
      stage('Stage1') {
         steps {
            build (job: 'job1')
         }
      }
   }
}

You do not really need to parameterize the downstream pipelines but can still pass the variable as a parameter from the upstream and access it in the downstream.您实际上不需要参数化下游管道,但仍然可以将变量作为参数从上游传递并在下游访问它。

Upstream pipeline上游管道

pipeline {
    agent any
    environment {
       TEST_VAR = 'hello_world'
    }
    stages {
        stage('Build-downstream-job') {
            steps {
                build job: 'downstream-job', parameters: [string(name: 'TEST_VAR', value: env.TEST_VAR)], wait: false
            }
        }
    }
}

Downstream pipeline下游管道

pipeline {
    agent any
    stages {
        stage('Get-test-var') {
            steps {
                println(params.TEST_VAR)
            }
        }
    }
}

Downstream pipeline console output下游管道控制台output

[Pipeline] stage
[Pipeline] { (Get-test-var)
[Pipeline] echo
hello_world
[Pipeline] }
[Pipeline] // stage

You should try adding a '$' before TEST_VAR:您应该尝试在 TEST_VAR 之前添加一个“$”:

environment {
     TEST_VAR = '$TEST_VAR'
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM