jenkinsjenkins-pipelinejenkins-docker

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


Suppose I have a dockerized pipeline with multiple steps. The docker container is defined in the beginning of 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
    }
  }
}

I would like to execute some git commands in a post-build action. The problem is that gradle image does not have git executable.

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

How can I execute it on Docker host still using gradle container for all other build steps? Of course I do not want to explicitly specify container for each step but that specific post-post action.


Solution

  • Ok, below is my working solution with grouping multiple stages (Build and Test) in a single dockerized stage (Dockerized gradle) and single workspace reused between docker host and docker container (see 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
        }
      }
    }