jenkins Kubernetes代理上的声明性管道动态、并行阶段?

qcbq4gxm  于 2022-11-02  发布在  Jenkins
关注(0)|答案(2)|浏览(293)

一月一日

我的概念证明。

pipeline {
  agent {
    label 'master'
  }
  stages {
    stage('Test') {
      steps {
        script {
          // The would be dynamically determined.
          projects = [
            [ name: 'project1', dir: 'path/1' ],
            [ name: 'project2', dir: 'path/2' ],
            [ name: 'project3', dir: 'path/3' ]
          ]

          projectStages = [:]

          projects.each { project ->          
            projectStages[project.name] = node {
              agent {
                kubernetes {
                  // Load a pod definition from a shared library.
                  yaml libraryResource('my-agent.yaml')
                }
              }
              stages {
                stage("Test $project.name") {
                  steps {
                    container('my-build-container') {
                      echo "Running: $project.name"
                      // Hostnames should be different (one for each project/pod).
                      sh('hostname')
                    }
                  }
                }
              }
            }
          }

          parallel projectStages
        }
      }
    }
  }
}

它会卡在projects.each行上并无限期挂起。

12:52:38  [Pipeline] node
12:52:53  Still waiting to schedule task
12:52:53  ‘Jenkins’ is reserved for jobs with matching label expression
etc...
ej83mcc0

ej83mcc01#

这是我找到的解决方案。
我有一个正确的想法,但是语法有点偏离。下面是我最终得到的结果(它像预期的那样并行构建和运行)。

pipeline {
  agent {
    label 'master'
  }
  stages {
    stage('Test') {
      steps {
        script {
          // These would be dynamically determined.
          projects = [
            [ name: 'project1', dir: 'path/1' ],
            [ name: 'project2', dir: 'path/2' ],
            [ name: 'project3', dir: 'path/3' ]
          ]

          projectStages = [:]

          echo "Found projects:\n$projects"

          projects.each { project ->
            projectStages[project.name] = generateStage(project.name, project.dir)
          }

          echo 'running...'

          parallel projectStages

          echo 'done...'
        }
      }
    }
  }
}

def generateStage(name, dir) {
  def podLabel = "my-test-pod-$name"
  return {
    stage("Test $name") {
      script {
        podTemplate(
          label: podLabel,
          yaml: libraryResource('my-agent.yaml')
        ) {
          node(podLabel) {
            container('my-build-container') {
              // Execute some steps in this container first.
              echo "Running: $name at $dir"
            }
            container('my-test-container') {
              // Execute some steps in this container next.
              sh('hostname')
            }
          }
        }
      }
    }
  }
}

还有Jenkins:

px9o7tmv

px9o7tmv2#

为什么要这么复杂呢?只要在你的流水线中使用并行步骤就可以了。示例在官方文档www.example.com中https://www.jenkins.io/doc/book/pipeline/syntax/#parallel

相关问题