post 步骤中的并行执行

Parallel execution inside the post step

我正在同一个管道中构建 2 个不同的环境,我想同时对两个环境进行清理。

据我了解,并行在 post 步骤中不起作用:post step parallel.

有什么建议吗?我的代码示例:

post {
    always {
        script{
            cleanup(env1)
            cleanup(env2)
        }
    }
}


def cleanup(env) {
    withEnv(env) {
        sh "./cleanup.py"
    }
}    

parallel 关键字可以在 post 条件下工作,只要它被封装在 script 块中,因为 script 块只是脚本化管道,可让您 运行 在任何需要的地方并行执行。
以下应该可以正常工作:

 post {
    always{
        script {
            def environments = ['env1', 'env2', 'env3']
            parallel environments.collectEntries {
                ["Cleanup ${it}" : {
                    cleanup(it)
                }]
            }
        }
    }
}


def cleanup(env) {
    withEnv(env) {
        sh "./cleanup.py"
    }
}  

如果 post 部分中的步骤需要在特定代理上 运行,请不要忘记使用 node 关键字分配代理。

在我看来,一个更好的主意是事后清理,在您可能将节点丢失给另一项工作之前:

parallel {
    stage('env1') {
        agent { node { label "env1" }}
        steps {
            script {
                println "Inside env1"   
            }
        }
        post {
            cleanup { script { my_cleanup_func("env1") } }
        }
    }
    stage('env2') {
        agent { node { label "env2" }}
        steps {
            script {
                println "Inside env2"   
            }
        }
        post {
            cleanup { script { my_cleanup_func("env2") } }
        }
    }
...
def my_cleanup_func(String env) {
    // ...
}