使用参数化开关的Jenkins Job DSL gradle闭包

mf98qq94  于 2023-03-22  发布在  Jenkins
关注(0)|答案(1)|浏览(150)

我正在尝试使用JJ.DSL创建一个Jenkins作业。我正在尝试创建一个逗号分隔的字符串,其中包含我需要运行的模拟。这是作业代码:

job("run-simulations") {
  parameters {
    choiceParam('targetEnvironment', ['stage', 'dev'], 'Select the target environment')
    booleanParam('s1', true, 'include simulation 1')
    booleanParam('s2', true, 'include simulation 2')
    booleanParam('s3', true, 'include simulation 3')
    booleanParam('s4', true, 'include simulation 4')
  }
  steps {
    gradle {
      useWrapper true
      tasks 'clean runPerformanceTest'
      switches '''
          -DtargetEnvironment=\${targetEnvironment}
          -Dsimulations=${getSimulations(${s1}, ${s2}, ${s3}, ${s4})}
      '''
    }
  }
}

static def getSimulations(s1, s2, s3, s4) {
  String simulations = [
      s1 ? "Simulation1" : "",
      s2 ? "Simulation2" : "",
      s3 ? "Simulation3" : "",
      s4 ? "Simulation4" : ""
  ]
  
  return simulations.join(",")
}

我得到了这个结果:

gradlew -DtargetEnvironment=dev -Dsimulations=${getSimulations(true, true, true, true)}

先谢了。

vkc1a9a2

vkc1a9a21#

我使用GString示例,因为我的计算机上没有工作Gradle:

pipeline{
    agent{label 'master'}
    stages{
        stage('1'){
            steps {
    script{
        def targetEnvironment="value1"
        def s1 = true
        def s2 = true
        def s3 = true
        def s4 = true
      String test1 = """
          -DtargetEnvironment=${targetEnvironment}
          -Dsimulations=${(getSimulations("$s1", "$s2", "$s3", "$s4"))}
      """
      echo test1
    }
    
  }
}
}
}

def getSimulations(s1, s2, s3, s4) {
  List<String> simulations = [
      s1 ? "Simulation1" : "",
      s2 ? "Simulation2" : "",
      s3 ? "Simulation3" : "",
      s4 ? "Simulation4" : ""
  ]
  
  return simulations.join(",")
}

你需要使用圆括号来调用函数,并在双引号内传递参数。你还需要在getSimulations函数中使用List<String>类型。
然而,为了更清晰,我将从该位置提取函数并仅传递结果变量:

def targetEnvironment="value1"
        def s1 = true
        def s2 = true
        def s3 = true
        def s4 = true
        def simParams = getSimulations(s1, s2, s3, s4)
      String test1 = """
          -DtargetEnvironment=${targetEnvironment}
          -Dsimulations=${simParams}
      """
      echo test1

相关问题