Jenkins post 部分(声明性管道)下的 运行 docker 是否有任何可能的解决方案?

Is there any possible solution to run docker under post section (declarative pipeline) on Jenkins?

我已经尝试 运行 docker 脚本通过脚本管道将测试报告发送到 slack。 但是,我不知道我们如何 运行 docker 脚本在分支为 master

时使用声明性管道脚本将测试报告发送到 slack

这是我试过的管道脚本

def today = new Date()
def format = today.format('MM_dd_yyyy_HH_mm')

pipeline {
   agent {
        docker {
                            label 'master'
                            image 'postman/newman:latest'
                            args '--entrypoint=\'\' -u root:root'
        }
   }

    options {
        disableConcurrentBuilds()
        buildDiscarder(logRotator(numToKeepStr: '2'))
    }
    stages {

         stage('Build')
         {
             steps{
                   sh "npm install -g newman-reporter-html"
                   sh "npm install -g newman-reporter-htmlextra"
             }
         }
 
    }
    post {
        always {
            script {
                if (env.BRANCH_NAME == 'master')
                {
                                     def currentResult = currentBuild.result == 'SUCCESS' ? 'success' : 'failure'
                                     withCredentials([string(credentialsId: '*****', variable: '****')]) {
                                     docker.image('mikewright/slack-client:latest')
                                         .run('-e SLACK_TOKEN=$TOKEN -e SLACK_CHANNEL=#devops_major_app',
                                             "\"${env.JOB_NAME}/${env.BRANCH_NAME} - Build#${env.BUILD_NUMBER}\n Status: ${currentResult}\n ${env.BUILD_URL}\"")
                                     }
                                     echo 'Already send slack message'
                }

            }

        }
    }

}

日志中出现错误

/var/lib/jenkins/workspace/Major-mobileapp-test_master@tmp/durable-a70f07be/script.sh: line 1: docker: not found

我想问题出在 docker 图像中缺少 docker 工具 postman/newman:latest.

因为您的案例是关于在 docker 中使用 docker。

您可以尝试使用 'agent' 部分在 post 步骤中使用另一个安装了 docker 工具的代理,以这个为例。

你可以像我下面的例子那样做:

我的 build 阶段和 post always 使用不同的 docker 构建代理。

pipeline {
    agent none; // none is expected here because out goal is to use different build agent across
    stages {
        stage('build') {
            agent {
                docker {
                    image 'maven:3-alpine'
                }
            }
            steps {
                sh "mvn -v"
            }
        }
    }
    post {
        always {
            script {
                docker.image('alpine').inside("-u 0:0") {
                    sh "apk update"
                }
            }
        }
    }
}