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

时间:2019-02-01 17:39:31

标签: docker jenkins docker-compose jenkins-pipeline

我正在尝试使用标签或versions标记我的docker容器。我正在尝试使用Jenkins声明一个字符串参数来为我做这件事。

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

image: api:"${version}"

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

在Jenkins管道中,我有一个名为version的字符串参数,默认值为LASTEST。但是我希望能够输入v1v2,这就是容器使用的标签。

结束语是执行蓝绿色部署的能力。

2 个答案:

答案 0 :(得分:0)

问题

  

在我的Jenkins管道中,我有一个名为version的字符串参数,默认为LASTEST。但是我希望能够输入v1或v2,这就是容器使用的标签。

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

解决方案

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

提示

docker-compose.yml中,您可以使用bash扩展为使用的变量分配默认值,例如:

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

或者如果您想要显式错误

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

答案 1 :(得分:0)

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

# 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']
        ]
    ])
}
# 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"]

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

Jenkins console output

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

相关问题