groovy Jenkins:参数化的选择字符串为空

72qzrwbm  于 2022-11-01  发布在  Jenkins
关注(0)|答案(2)|浏览(326)
def projectsString = ''

 stage('debug') {
       when {
         branch 'master'
       }

       steps {
         script {
           def files = findFiles()
           files.each {
             f ->
               if (f.directory) {
                 projectsString = projectsString + f.name + "\\" + "n "

                 echo projectsString
               }
           }
         }
       }
     }

     stage('debug2') {
       when {
         branch 'master'
       }
       input {

         message "Choose"
         ok "Submit"
         parameters {
           choice(name: 'CHOICES', choices: "${projectsString}", description: 'Please Select One')
         }

       }

       steps {
         script {

           echo "Selected choice is : ${params.CHOICES}"
         }
       }
     }

debug2阶段,没有选择,projectsString,即使我在debug阶段用值填充它,也不知道我做错了什么,它也是一个全局变量
在调试阶段也有一个echo projectsString,当我在debug2阶段直接硬编码该字符串时,选择显示正确

kkih6yb8

kkih6yb81#

如果简单变量在另一个阶段中为空,请尝试as in here,即env var替代项:

def env.projectsString = ''
...
env.projectsString = ${projectsString} + f.name + "\\" + "n "
...
choice(name: 'CHOICES', choices: "${projectsString}", description: 'Please Select One')
g6ll5ycj

g6ll5ycj2#

要在多个阶段中可用,变量需要是环境变量:

environment {
    VARIABLE = "initial value"
}

并且您对它所做的更改必须采用此格式才能在其他阶段中使用:

env.VARIABLE = "new value"

在您的情况下:

pipeline {
    agent any

    environment {
        projectsString = "initial value"
    }

    stages{
        stage('debug') {
            when {
                branch 'master'
            }

            steps {
                script {
                def files = findFiles()
                files.each {
                    f ->
                    if (f.directory) {
                        env.projectsString = projectsString + f.name + "\\" + "n "

                        echo projectsString
                    }
                }
                }
            }
        }

        stage('debug2') {
            when {
                branch 'master'
            }
            input {

                message "Choose"
                ok "Submit"
                parameters {
                    choice(name: 'CHOICES', choices: "${projectsString}", description: 'Please Select One')
                }

            }

            steps {
                script {

                echo "Selected choice is : ${params.CHOICES}"
                }
            }
        }
    }
}

有关https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables详细信息,请访问www.example.com和https://www.jenkins.io/doc/pipeline/tour/environment/

相关问题