【问题标题】:Using a docker command as an variable in a Jenkins sh script?在 Jenkins sh 脚本中使用 docker 命令作为变量?
【发布时间】:2022-01-20 14:10:55
【问题描述】:

我正在开发一个 CI/DC 管道,其中有一个 DEV、TEST 和 Prod 服务器。使用 Jenkins 流水线,我将最新的图像部署到我的 DEV-Server 上。现在我想通过读出 sha256 id 来获取我的 DEV-Server 的图像并将其放在我的 TEST-Server 上。

为此我有一个 Jenkins 流水线:

    pipeline {
        
        agent any
        tools {
            dockerTool 'docker-19.03.9'
        }
        
        environment {
            
        }
        
        stages {
            stage('DeployToTEST-Angular') {
                steps {
                    script {
                        echo 'Deploying image...'
                        sh 'docker stop mycontainertest'
                        sh 'docker rm mycontainertest'
                        sh 'docker run -d --name mycontainertest [cant show the envirmoments i give with] --restart always angular:latest'
                    }
                }
                
            }
    }

如你所见,我目前使用 :latest 标签,但我想要这样的:

pipeline {
    
    agent any
    tools {
        dockerTool 'docker-19.03.9'
    }
    
    environment {
        
    }
    
    stages {
        stage('DeployToTEST-Angular') {
            steps {
                script {
                    echo 'Deploying image...'
                    sh 'docker stop mycontainertest'
                    sh 'docker rm mycontainertest'
                    sh 'docker run -d --name mycontainertest [cant show the envirmoments i give with] --restart always \$imageofDev'
                }
            }
            
        }
}

$imageofDev = docker 检查 mycontainerdev | grep -o 'sha256:[^"]*' // 此命令有效并返回原始 sha256 编号

以便它使用我的开发图像的实际 sha256 编号

我不知道如何定义这个变量,然后在这个 Jenkins 管道中使用它的值。我该怎么做?

【问题讨论】:

    标签: docker jenkins sh


    【解决方案1】:

    在构建镜像时,选择一个您以后可以记住的镜像名称和标签。 Jenkins 提供了几个environment variables 可以用来构造这个,比如BUILD_NUMBER;在multibranch pipeline 中,您还可以访问BRANCH_NAMECHANGE_ID;或者你可以直接在你的管道代码中运行git

    def shortCommitID = sh script: 'git rev-parse --short HEAD', returnStdout: true
    def dockerImage = "project:${shortCommitID.trim()}"
    def registry = 'registry.example.com'
    def fullDockerImage "${registry}/${dockerImage}"
    

    现在您已经知道要在任何地方使用的 Docker 映像名称了;您永远不需要去查找图像 ID。使用scripted pipeline Docker integration,例如:

    docker.withRegistry("https://${registry}") {
      def image = docker.build(dockerImage)
      image.push
    }
    

    既然你知道 registry/image:tag 的名字,你也可以在其他 Jenkins 指令中使用它

    def containerName = 'container'
    
    // stop an old container, if any
    sh "docker stop ${containerName} || true"
    sh "docker rm ${containerName} || true"
    
    // start a new container that outlives this pipeline
    sh "docker run -d --name ${containerName} ${fullDockerImage}"
    

    【讨论】:

    • 谢谢,我自己找到了答案,但你的想法对我有帮助:)
    猜你喜欢
    • 1970-01-01
    • 2019-01-22
    • 2020-12-24
    • 2019-09-24
    • 2017-08-02
    • 2017-09-11
    • 2013-09-26
    • 2010-10-22
    • 1970-01-01
    相关资源
    最近更新 更多