Jenkins脚本:如果条件等于失败,则在POST块中运行新容器

nzkunb0c  于 2023-04-05  发布在  Jenkins
关注(0)|答案(1)|浏览(133)

我已经按照Jenkins documentation在容器中成功运行了Jenkins和docke:dind。我有一个Jenkins脚本来构建Puppeteer镜像并运行容器来测试我的前端。我想添加逻辑,如果测试失败,则终止当前的Puppeteer容器并运行新的容器。
以下是我的Jenkins脚本:

pipeline {
    agent {
        dockerfile {
            filename 'Dockerfile'
            dir 'MyDockerFileFolder'
            additionalBuildArgs  '--build-arg UID=$(id -u) --build-arg GID=$(id -g) -t puppeteer-testing-image'
        }
    }

    stages {
        stage('Build') {
            steps {
                sh 'npm ci'
            }
        }
        stage('Test') {
            steps {
                sh 'npm run myPuppeteerTest'
            }
            post {
                failure {
                    // I would like to terminate puppeteer container here
                    // and run the new container here
                }
            }    
        }
    }
}

如果我只是简单地在故障块中添加此命令,它将无法工作,因为该命令实际上是在Puppeteer容器中运行的,而Puppeteer容器没有Docker命令。

sh 'docker run -name newContainer container:latest'

我对Jenkins非常陌生,任何帮助都很感激!

oknwwptz

oknwwptz1#

对于您的情况,它不适合使用顶级代理,您可以尝试如下

def testContainer

pipeline {
    agent any

    stages {
            stage('Prepare') {
                steps {
                    testContainer = docker
                        .build(
                            '<image tag>', 
                            '''-f MyDockerFileFolder/Dockerfile \
                                 --build-arg UID=$(id -u) \
                                 --build-arg GID=$(id -g) \
                                 -t puppeteer-testing-image'''
                        )
                        .run('-u $(id -u):$(id -g) -v /etc/passwd:/etc/passwd -dt', 'cat')
                }
            }
        stage('Build') {
            steps {
                sh """
                    docker exec -it ${testContainer.id} npm ci
                """
            }
        }
        stage('Test') {
            steps {
                sh """
                    docker exec -it ${testContainer.id} npm run myPuppeteerTest
                """
            }
            post {
                failure {
                    // I would like to terminate puppeteer container here
                    // and run the new container here
                    if(testContainer) {
                        sh """
                            docker stop ${testContainer.id}
                            docker run <for new container>
                        """
                    }
                }
            }    
        }
    }
}

相关问题