如何在Windows Server 2016/2019的Jenkins中运行Docker构建?

时间:2019-05-03 13:23:33

标签: windows docker jenkins

我想在Docker容器中的Windows节点上运行Jenkins构建。

1 个答案:

答案 0 :(得分:0)

对于那些正在寻找即用型答案而不是无用的文档页面的参考的人,下面是一个如何在Windows 2016/2019上运行Docker构建的Jenkinsfile片段:

// invokeDocker.groovy
def call(image, cmd) {
    powershell """
        docker run `
          --rm `
          -w "${env.WORKSPACE}" `
          -v "${env.WORKSPACE}:${env.WORKSPACE}:rw" `
          -e "WORKSPACE=${env.WORKSPACE}" `
          -e "BUILD_NUMBER=${env.BUILD_NUMBER}" `
          $image powershell -C "$cmd"
    """
}

您应该使用共享库,例如。使用多阶段管道:

// runDockerStages.groovy
def call(Map pipelineParams) {

    if(!pipelineParams){
        pipelineParams = [:]
    }

    pipeline {
        agent { label "DOCKER-BUILDER" && "SERVER2019" }

        environment {
            SCRIPTS="__scripts"
        }

        options {
            timeout(time: pipelineParams.timeoutMinutes ? pipelineParams.timeoutMinutes : 180, unit: 'MINUTES')
        }

        stages {
            stage('Deploy scripts'){
                steps {
                    initializeWorkspace();
                }
            }

            stage('Trigger custom build stages'){
                steps {
                    executeDockerBuildStages(pipelineParams.Stages);
                }
            }

            stage('Publish'){
                steps{
                    script{
                        publishAllArtifacts();
                    }
                }
            }
        }
        post{
            success{
                // Set latest build URL on Jira case
                updateJira();
            }
        }
    }
}

void executeDockerBuildStages(stageInfos) {
    stageInfos.each { dockerStage ->
        echo("---- About to run [${dockerStage.Title}] stage ----")
        script {
            stage(dockerStage['Title']) {
                invokeDocker(dockerStage['DockerImage'], dockerStage['Script'])
            }
        }
    }
}

您的Jenkins文件将如下所示:

runDockerStages(
  [ 
    Stages: [
      [ Title: 'Prepare', DockerImage: "imagine/jenkins-pipeline/buildbase-windows:1.0.0-windowsservercore-1809", Script: ". .\\build\\build.Prepare.ps1" ],
      [ Title: 'Test', DockerImage: "imagine/jenkins-pipeline/dotnetcore:2.2.203-windowsservercore-1809", Script: ". .\\build\\build.Test.ps1" ],
      [ Title: 'UI', DockerImage: "imagine/jenkins-pipeline/nodejs:10.15.0-windowsservercore-1809", Script: ". .\\build\\build.ui.ps1" ],
      [ Title: 'Service', DockerImage: "imagine/jenkins-pipeline/dotnetcore:2.2.203-windowsservercore-1809", Script: ". .\\build\\build.service.ps1" ]
  ]
)