使用Jenkins管道参数标记docker映像

tagging docker images with Jenkins pipeline parameter

我正在尝试标记我的docker映像`。我正在使用Jenkins通过声明一个字符串参数来为我做这件事。

docker-compose.yml文件中,我的图像如下所示:

image: api:"${version}"

我收到一个错误消息,说标签不正确。

在我的Jenkins管道中,我有一个名为version的字符串参数,默认值为LATEST。但是,我希望能够输入将用作图像标签的v1v2

我正在使用蓝绿色部署。


您可以在管道中使用withEnv在构建环境中设置VERSION,例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Jenkinsfile
---
stage('build'){
    node('vagrant'){
        withEnv([
           'VERSION=0.1'
        ]){
            git_checkout()
            dir('app'){
                ansiColor('xterm') {
                    sh 'mvn clean install'
                }
            }
            // build docker image with version
            sh 'docker build --rm -t app:${VERSION} .'
        }
    }
}

def git_checkout(){
    checkout([
        $class: 'GitSCM',
        branches: [[name: '*/' + env.BRANCH_NAME]],
        doGenerateSubmoduleConfigurations: false,
        extensions: [
            [$class: 'SubmoduleOption', disableSubmodules: false, parentCredentials: true, recursiveSubmodules: false, reference: '', trackingSubmodules: true],
            [$class: 'AuthorInChangelog'],
            [$class: 'CloneOption', depth: 0, noTags: false, reference: '', shallow: false]
        ],
        submoduleCfg: [],
        userRemoteConfigs: [
            [credentialsId: '...', url: 'ssh://vagrant@ubuntu18/usr/local/repos/app.git']
        ]
    ])
}
1
2
3
4
5
6
7
8
9
10
11
# Dockerfile
---
FROM ubuntu:18.04

RUN apt update && \\
    apt install -y openjdk-11-jre && \\
    apt clean

COPY app/special-security/target/special-security.jar /bin

ENTRYPOINT ["java","-jar","/bin/special-security.jar"]

在Jenkins构建环境中设置的版本号由docker build命令使用。

Jenkins

注意:我使用maven构建的java应用程序(例如mvn clean install)纯粹出于示例目的,该代码可从https://stackoverflow.com/a/54450290/1423507获得。此外,Jenkins控制台中的彩色输出需要使用AnsiColor插件,如https://stackoverflow.com/a/53227633/1423507所述。最后,在此示例中不使用docker-compose,在环境中设置版本没有区别。


问题

In my Jenkins pipeline I have a string parameter named version with default LASTEST. However I want to be able to enter v1 or v2 and that is the tag the container uses.

假设docker compose在您的Jenkins管道内部运行,则${version} you use in docker-compose.yml`必须在Jenkins管道的shell环境中可用,否则将没有任何结果,因此出现错误,提示您标记无效。

解决方案

很抱歉,但是我对Jenkins并不熟悉,所以我无法告诉您如何在运行shell环境中正确设置${version}的值,因此您需要对此进行一些搜索。

小费

作为docker-compose.yml中的一个技巧,您可以使用bash扩展将默认值分配给您使用的变量,例如:

1
image: api:"${version:-latest}"

或者如果您想要显式错误

1
image: api:"${version? Mipssing version for docker image!!!}"