1

假设我有一个包含多个步骤的 dockerized 管道。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
    }
  }
}

我想git在构建后操作中执行一些命令。问题是gradle图像没有git可执行文件。

script.sh:第 1 行:git:找不到命令

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

4

1 回答 1

6

好的,下面是我的工作解决方案,将多个阶段(构建和测试)分组到单个 dockerized 阶段(Dockerized gradle)和在 docker 主机和 docker 容器之间重用的单个工作区(请参阅reuseNode文档):

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
    }
  }
}
于 2020-07-21T17:49:32.727 回答