Change groovy variables inside shell executor in Jenkins pipeline

人盡茶涼 提交于 2019-12-11 03:34:37

问题


I have a Jenkins pipeline job where I am taking some build variables as input, and if the variables are not passed by the user, I execute a script and get the value of those variables. Later I have to use the value of these variables to trigger other jobs.

So my code looks something like this:

node {
withCredentials([[$class: 'StringBinding', credentialsId: 'DOCKER_HOST', variable: 'DOCKER_HOST']]) {

env.T_RELEASE_VERSION = T_RELEASE_VERSION
env.C_RELEASE_VERSION = C_RELEASE_VERSION
env.N_RELEASE_VERSION = N_RELEASE_VERSION
env.F_RELEASE_VERSION = F_RELEASE_VERSION

....

stage concurrency: 1, name: 'consul-get-version'
sh '''
        if [ -z ${T_RELEASE_VERSION} ]
        then
            export T_RELEASE_VERSION=$(ruby common/consul/services_prod_version.rb prod_t_release_version)
            aws ecr get-login --region us-east-1
            aws ecr list-images --repository-name t-server | grep ${T_RELEASE_VERSION}
        else
            aws ecr get-login --region us-east-1
            aws ecr list-images --repository-name t-server | grep ${T_RELEASE_VERSION}
        fi

.......


    't-integ-pipeline' : {
build job: 't-integ-pipeline', parameters: [[$class: 'StringParameterValue', name: 'RELEASE_VERSION', value: T_RELEASE_VERSION],
                                           [$class: 'BooleanParameterValue', name: 'FASTFORWARD_TO_DEPLOY', value: true]]
},

......

The issue is when I am triggering the main job with empty T_RELEASE_VERSION, the child build job t-integ-pipeline is triggered with an empty value of the RELEASE_VERSION parameter.

How can I change a groovy parameter inside a shell executor and then access it again in the groovy executor with the modified value?


回答1:


When using env-inject it was possible to store the values in the properties files and the inject them as environment variables. Couldn't find any easy way to do it in pipeline.

Here is a solution anyway, store the values to a file, and read the file from the pipeline. Then use eval or similar to transform it to an parsable object (hash).

Eval.me example: Serializing groovy map to string with quotes

Write/Read to file example: https://wilsonmar.github.io/jenkins2-pipeline/

EDIT Manish solution for readability:

sh 'ruby common/consul/services_prod_version.rb prod_n_release_version > status' 
N_RELEASE_VERSION_NEW = readFile('status').trim() 
sh 'ruby common/consul/services_prod_version.rb prod_q_release_version > status' 
Q_RELEASE_VERSION_NEW = readFile('status').trim()


来源:https://stackoverflow.com/questions/40629924/change-groovy-variables-inside-shell-executor-in-jenkins-pipeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!