jenkins+gitlab+docker 构建maven项目h

2019-11-21  本文已影响0人  _str_

准备jenkins容器和maven容器

- jenkinsci/blueocean: latest    -jenkins容器需要有宿主机docker的root权限才能创建另一个容器
···
- type: bind
        source: /var/run/docker.sock
        target: /var/run/docker.sock
···
- maven:3-alpine

需要准备一个maven项目 这里准备了一个简单的hello world的项目 simple-java-maven-app

simple-java-maven-app
编写jenkinsfile

手动编写Jenkinsfile

pipeline {
    agent none
    stages {
        stage('build') {
            agent {
                docker {
                    image 'maven:3-alpine' 
                    args '-v /root/.m2:/root/.m2' 
                }
            }
            steps {
                sh 'mvn -B -DskipTests clean package'
            }
        }
        stage('test') {
            agent any
            steps {
                sh 'ls "${WORKSPACE}"'
            }
        }
    } 
}

jenkins中新建任务

新建任务
页面编写 描述信息 流水线配置信息

结果

image.png build过程 成功 jar包构建成功 成功将项目拉取到jenkins服务器的workspace中

使用项目中的jenkinsfile

新建任务的步骤和上面的一样
只需修改一下流水线中的脚本路径就可以了

gitlab仓库中文件路径 修改路径 build结果 test结果 deliver过程 最终结果

项目中的jenkinsfile

pipeline {
    agent {
        docker {
            image 'maven:3-alpine'
            args '-v /root/.m2:/root/.m2'
        }
    }
    stages {
        stage('Build') {
            steps {
                sh 'mvn -B -DskipTests clean package'
            }
        }
        stage('Test') {
            steps {
                sh 'mvn test'
            }
            post {
                always {
                    junit 'target/surefire-reports/*.xml'
                }
            }
        }
        stage('Deliver') {
            steps {
                sh './jenkins/scripts/deliver.sh'
            }
        }
    }
}

script中脚本

#!/usr/bin/env bash

echo 'The following Maven command installs your Maven-built Java application'
echo 'into the local Maven repository, which will ultimately be stored in'
echo 'Jenkins''s local Maven repository (and the "maven-repository" Docker data'
echo 'volume).'
set -x
mvn jar:jar install:install help:evaluate -Dexpression=project.name
set +x

echo 'The following complex command extracts the value of the <name/> element'
echo 'within <project/> of your Java/Maven project''s "pom.xml" file.'
set -x
NAME=`mvn help:evaluate -Dexpression=project.name | grep "^[^\[]"`
set +x

echo 'The following complex command behaves similarly to the previous one but'
echo 'extracts the value of the <version/> element within <project/> instead.'
set -x
VERSION=`mvn help:evaluate -Dexpression=project.version | grep "^[^\[]"`
set +x

echo 'The following command runs and outputs the execution of your Java'
echo 'application (which Jenkins built using Maven) to the Jenkins UI.'
set -x
java -jar target/${NAME}-${VERSION}.jar   ----最终在maven容器中执行这个命令就能看到helloworld了

注意

在写jenkinsfile的时候一定要注意格式缩进问题
在全局agent置为none的时候需要在每个stages中申明一下agent 不然会报错

上一篇 下一篇

猜你喜欢

热点阅读