首页 > 解决方案 > 可锁定资源插件 Jenkinsfile -> 动态

问题描述

这是一个声明性的 Jenkins-Pipeline。

使用可锁定资源插件(https://plugins.jenkins.io/lockable-resources/)我想动态锁定多个阶段,具体取决于用户在参数部分选择的环境。这就是我希望这样做的方式:

    pipeline {
    parameters {
        choice choices: ['---', 'prod', 'test'], description: 'Environment', name: 'environment'
    }
    stage('MY_APPLICATION') {
        options{
            lock('resource': "${params.environment}")
        }
        stages {
            stage('TEST') {
                when { expression { "${params.environment}" == 'prod' } }
                steps { ... }
            }
            stage('PROD') {
                when { expression { "${params.environment}" == 'test' } }
                steps { ... }
            }
        }
    }
    }

但我无法访问选项块中的参数,它始终使用默认值。有谁知道如何根据环境变量动态锁定资源?

标签: jenkinsjenkins-pipelinejenkins-groovy

解决方案


我设法像这样解决它:

在选项块中,有可用的 $currentBuild 变量,这样就可以动态锁定资源:

pipeline {
 parameters {
     choice choices: ['---', 'prod', 'test'], description: 'Environment', name: 'environment'
 }
 stage('MY_APPLICATION') {
     options{
         lock('resource': "${currentBuild.getRawBuild().getEnvironment(TaskListener.NULL).environment}")
     }
     stages {
         stage('TEST') {
             when { expression { "${params.environment}" == 'prod' } }
             steps { ... }
         }
         stage('PROD') {
             when { expression { "${params.environment}" == 'test' } }
             steps { ... }
         }
     }
 }
}

推荐阅读