Search code examples
dockerjenkinsgroovyjenkins-pipelinejenkins-groovy

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


I have try to run docker script to send test report to slack with script pipeline. However, I don't have any clue how can we run docker script to send test report to slack with declarative pipeline script when branch is master

Here is pipeline script what i have try

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'
                }

            }

        }
    }

}

Here is error on log

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

Solution

  • you can do like my below example:

    my build stage and post always use different docker build agent.

    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"
                    }
                }
            }
        }
    }