如果 Jenkins 管道 dockerized,如何在 docker 主机上执行单步或 post-build 操作?

How to execute single step or post-build action on a docker host if Jenkins pipeline is dockerized?

假设我有一个包含多个步骤的 docker 化管道。 docker容器定义在Jenkinsfile:

开头
pipeline {
  agent {
    docker {
      image 'gradle:latest'
    }
  }

  stages {
    // multiple steps, all executed in 'gradle' container 
  }

post {
    always {
      sh 'git whatever-command' // will not work in 'gradle' container
    }
  }
}

我想在 post-build 操作中执行一些 git 命令。问题是 gradle 映像没有 git 可执行文件。

script.sh: line 1: git: command not found

如何在 Docker 主机上执行它仍然使用 gradle 容器进行所有其他构建步骤?当然,我不想为每个步骤明确指定容器,而是为特定的 post-post 操作指定容器。

好的,下面是我的工作解决方案,将多个阶段(构建和测试)分组到一个 docker 化阶段(Docker 化 gradle)和 docker 主机之间重复使用的单个工作区和 docker 容器(参见 reuseNode docs):

pipeline {
  agent {
    // the code will be checked out on out of available docker hosts
    label 'docker'
  }

  stages {
    stage('Dockerized gradle') {
      agent {
        docker {
          reuseNode true // < -- the most important part
          image 'gradle:6.5.1-jdk11'
        }
      }
      stages{
        // Stages in this block will be executed inside of a gradle container
        stage('Build') {
          steps{
            script {
                sh "gradle build -x test"
            }
          }
        }
        stage('Test') {
          steps{
            script {
              sh "gradle test"
            }
          }
        }
      }
    }
    stage('Cucumber Report') {
      // this stage will be executed on docker host labeled 'docker'
      steps {
        cucumber 'build/cucumber.json'
      }
    }
  }

  post {
    always {
      sh 'git whatever-command' // this will also work outside of 'gradle' container and reuse original workspace
    }
  }
}