jenkins 如何为列表中的每个目录并行化terraform命令?

wsxa1bj1  于 2023-04-19  发布在  Jenkins
关注(0)|答案(1)|浏览(176)

目前,我正在抓取一个目录的字符串列表,并单独导航到每个目录-然后执行我的terraform操作。这需要很长时间才能运行,因为它会一个接一个地遍历每个目录。
由于我不能在脚本块中使用“parallel”,有没有一种解决方法可以同时导航(和执行)到我的所有目录?

pipeline {
        agent {
            docker { 
                image 'hashicorp/terraform:latest' 
                args '--entrypoint="" --platform linux/amd64 -d'
            }
        }             
      stages {
        stage('Example') {
          steps {
            script {
                def directories = getDirectories("$WORKSPACE/modules/")
                directories.each{ f ->
                    dir ("${f.name}") {
                        sh ('terraform init')
                        sh ('terraform validate')
                    }    
                }    
            }
          }
        }
      }
    }
    
    @NonCPS
    def getDirectories(path) {
        def dir = new File(path)
        def dirs = []
        dir.traverse(type: groovy.io.FileType.DIRECTORIES, maxDepth: 0) { d ->
            dirs.add(d) 
        }
        return dirs
    }
qfe3c7zg

qfe3c7zg1#

https://www.jenkins.io/blog/2017/09/25/declarative-1/#parallel-stages
parallelJenkins步骤可以接受[name, {steps}]Map的想法

pipeline {
        agent {
            docker { 
                image 'hashicorp/terraform:latest' 
                args '--entrypoint="" --platform linux/amd64 -d'
            }
        }             
      stages {
        stage('Example') {
          steps {
            script {
                def directories = getDirectories("$WORKSPACE/modules/")
                parallel directories.collectEntries{ f ->
                    [f.name, {
                        dir("$f") {
                            sh ('terraform init')
                            sh ('terraform validate')
                        }
                    }]
                }   
            }
          }
        }
      }
    }

PS:不确定collectEntries是否是CPS安全的
UPD:你的问题在互联网上有多种答案...
https://devops.stackexchange.com/questions/3073/how-to-properly-achieve-dynamic-parallel-action-with-a-declarative-pipeline

相关问题