簡體   English   中英

在 Jenkins 管道中更改 shell 執行程序內的常規變量

[英]Change groovy variables inside shell executor in Jenkins pipeline

我有一個 Jenkins 管道作業,我將一些構建變量作為輸入,如果用戶沒有傳遞這些變量,我會執行一個腳本並獲取這些變量的值。 后來我不得不使用這些變量的值來觸發其他作業。

所以我的代碼看起來像這樣:

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]]
},

......

問題是當我用空的 T_RELEASE_VERSION 觸發主作業時,子構建作業 t-integ-pipeline 是用 RELEASE_VERSION 參數的空值觸發的。

如何更改 shell 執行程序中的 groovy 參數,然后在 groovy 執行程序中使用修改后的值再次訪問它?

使用 env-inject 時,可以將值存儲在屬性文件中並將它們作為環境變量注入。 在管道中找不到任何簡單的方法來做到這一點。

無論如何,這是一個解決方案,將值存儲到文件中,然后從管道中讀取文件。 然后使用 eval 或類似方法將其轉換為可解析的對象(哈希)。

Eval.me 示例:將groovy 映射序列化為帶引號的字符串

寫入/讀取文件示例: https : //wilsonmar.github.io/jenkins2-pipeline/

編輯 Manish 解決方案以提高可讀性:

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()

我找到了一種在shell中更改groovy變量的方法,無需將其存儲在文件中,這里有一個示例git-tag-message-plugin ,我使用這種方法如下:

script{
N_RELEASE_VERSION_NEW = getN_RELEASE_VERSION_NEW()
}


String getN_RELEASE_VERSION_NEW() {
    return sh(script: "ruby common/consul/services_prod_version.rb prod_n_release_version ", returnStdout: true)?.trim()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM