Jenkins详述-jenkins+gitlab+tomcat+sonarQube

目录

一、软件开发的生命周期

软件开发的周期又叫做SDLC(SoftWare Development Life Cycle),它是集合了计划、开发、测试和部署过程。

img

二、持续集成

所谓的持续集成指的是,频繁的将代码集成到主干。持续集成的目的就是为了让产品能够快速的迭代,同时还能保持高质量。为了保证高质量的持续集成,必须通过自动化测试,自动化部署来实现。

一个团队可以快速的从一个功能到另一个功能的快速迭代,就需要有一套快速且高度自动化的一个软件来实现这一需求。

img

三、Jenkins

Jenkins主要是用来做软件部署过程中的持续集成自动化的。

Jenkins是一款流行的开源持续集成工具,广泛用于项目开发,自动化部署,自动化测试等功能。

官网:https://www.jenkins.io/zh/

1、Jenkins的特点

  • 开源
  • 是由Java语言开发的
  • 简单并且易于安装
  • 分布式构建
  • 支持丰富的插件

2、持续集成流程

image.png

3、部署gitlab (代码托管服务器)

gitlab官网:https://about.gitlab.cn/install/

Gitlab是一个用于代码仓库管理系统的开源项目,使用Git作为代码的管理工具,并在此基础上搭建起来的一个web服务。

部署Gitlab最小的系统配置是,2核4GB。

3.1 安装软件

[root@localhost ~]# hostnamectl set-hostname gitlab
[root@localhost ~]# echo '106.14.16.228 gitlab' >> /etc/hosts

[root@localhost ~]# yum install -y curl policycoreutils-python openssh-server perl

[root@localhost ~]# vim /etc/yum.repos.d/gitlab-ce.repo
[gitlab-ce]
name=Gitlab CE Repository
baseurl=https://mirrors.tuna.tsinghua.edu.cn/gitlab-ce/yum/el$releasever/
gpgcheck=0
enabled=1

[root@localhost ~]# sudo yum makecache
[root@localhost ~]# sudo yum install gitlab-ce -y

3.2 配置软件

[root@localhost ~]# vim /etc/gitlab/gitlab.rb  # 修改以下选项
external_url 'http://192.168.13.62'
nginx['listen_port'] = 80

image-20220410170618522

image-20220416144107474

3.3 生成配置

[root@gitlab ~]# gitlab-ctl reconfigure
[root@gitlab ~]# gitlab-ctl start

3.4 登录gitlab

# 获取默认的密码,去浏览器访问IP登录gitlab,进入页面后右上角偏好设置中可以设置中文

[root@gitlab ~]# cat /etc/gitlab/initial_root_password | grep 'Password:'
Password: t30kqLek+paNa6nIWHy77iLkIYBIckXzJI5NQrIjtVs=

image-20220410171151911

image-20220410171321471

image-20220410171547671

4、Git (开源的分布式代码托管工具)

4.1 安装Git

Git是支持跨平台的.

4.1.1 window安装

# 下载连接如下,下载后直接安装在非系统盘即可。
https://github.com/git-for-windows/git/releases/download/v2.35.1.windows.2/Git-2.35.1.2-64-bit.exe

# 使用pycharm的话,可以在settings中如图下配置git

image-20220410172153061

image-20220409164329095

image-20220410170024939

image-20220410170137682

4.1.2 linux安装

[root@gitlab ~]# yum install git -y

4.2 git的使用

线下和线上相关的操作。

4.2.1 git的暂存区和缓冲区

代码文件编辑好之后使用'git add 文件名'加入缓存冲进入Git管理;使用'git commit -m "提交代码的注释"'进入缓存区;通过'git push origin 分支名称'提交到代码托管服务器。

image-20220410173506776

4.2.2 Git命令的使用

1、创建一个本地的git仓库

[root@localhost ~]# mkdir test
[root@localhost ~]# cd test/

2、初始化git仓库

[root@localhost test]# git init
Initialized empty Git repository in /root/test/.git/

[root@localhost test]# ll -a
total 0
drwxr-xr-x  3 root root  18 Apr  7 09:43 .
dr-xr-x---. 8 root root 243 Apr  7 09:42 ..
drwxr-xr-x  7 root root 119 Apr  7 09:43 .git

3、添加代码到缓冲区

[root@localhost test]# vim index.py
[root@localhost test]# ll
total 4
-rw-r--r-- 1 root root 22 Apr  7 09:44 index.py

[root@localhost test]# git add index.py

4、将代码从缓冲区删除

[root@localhost test]# git rm --cached index.py
rm 'index.py'

5、配置git邮箱和用户名

[root@localhost test]# git config --global user.name "Your Name"
[root@localhost test]# git config --global user.email you@example.com

6、提交到暂存区

[root@localhost test]# git commit -m '提交需要添加的注释' 

4.2.3 Git分支

1、创建分支

[root@localhost test]# git checkout -b test
Switched to a new branch 'test'

2、查看分支

[root@localhost test]# git branch
  master
* test

3、切换分支

[root@localhost test]# git checkout master
Switched to branch 'master'
[root@localhost test]# git branch
* master
  test

4.2.4 提交至代码托管服务

1、创建一个远程代码仓库

image.png

image-20220410215515119

image.png

2、登录远程代码仓库

image-20220410215609648

image-20220410220124424

image-20220410220057304

image-20220410220200348

3、将本地仓库与线上仓库建立连接

[root@localhost test]# git remote add origin git@192.168.13.62:root/jenkins.git

4、将本地代码提交至远程仓库

[root@localhost test]# git push origin master   # 格式:git push origin 分支名
The authenticity of host '192.168.13.62 (192.168.13.62)' can't be established.
ECDSA key fingerprint is SHA256:F3PfT4mMKcYBveN9o1NMvAU4wFh2dMsWe9B5Zlqiuqk.
ECDSA key fingerprint is MD5:bb:1b:ec:02:27:0f:93:72:ae:6d:5a:48:99:b7:87:58.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.13.62' (ECDSA) to the list of known hosts.
Counting objects: 6, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (6/6), 474 bytes | 0 bytes/s, done.
Total 6 (delta 0), reused 0 (delta 0)
To git@192.168.13.62:root/jenkins.git
 * [new branch]      master -> master

5、gitlab代码托管服务器简单使用

用户及用户组

image.png

img

img

6、Jenkins部署

Jenkins是使用Java开发的一款自动化部署的软件。

6.1 部署Java

jenkins是用java开发的,所以需要先部署依赖

[root@localhost ~]# hostnamectl set-hostname jenkins

# 备份源
[root@jenkins ~]# mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.bak

# 换源
[root@jenkins ~]# vi /etc/yum.repos.d/CentOS-Base.repo

# CentOS-Base.repo
#
# The mirror system uses the connecting IP address of the client and the
# update status of each mirror to pick mirrors that are updated to and
# geographically close to the client.  You should use this for CentOS updates
# unless you are manually picking other mirrors.
#
# If the mirrorlist= does not work for you, as a fall back you can try the
# remarked out baseurl= line instead.
#
#

[base]
name=CentOS-$releasever - Base
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/os/$basearch/
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7

#released updates
[updates]
name=CentOS-$releasever - Updates
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/updates/$basearch/
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7

#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/extras/$basearch/
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7

#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/centosplus/$basearch/
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7

[root@jenkins ~]# yum install java-1.8.0-openjdk* -y

6.2 部署Jenkins

[root@jenkins ~]# wget http://106.13.81.75/jenkins-2.249.1-1.1.noarch.rpm
[root@jenkins ~]# yum install jenkins-2.249.1-1.1.noarch.rpm -y

# 安装git工具
[root@jenkins ~]# yum install git -y

6.3 启动Jenkins

[root@jenkins nginx]# vim /etc/nginx/nginx.conf
include /etc/nginx/conf.d/*.conf;

[root@jenkins nginx]#vim /etc/nginx/conf.d/jenkins.conf
server {

  server_name _;
  listen 80;
  location / {
    proxy_pass http://127.0.0.1:8080;
	}
}

[root@jenkins conf.d]# nginx -t
[root@jenkins conf.d]# systemctl start nginx
[root@jenkins ~]# systemctl start jenkins 

image.png

image.png

6.4 Jenkins换源

# 切换至配置文件目录
[root@jenkins updates]# cd /var/lib/jenkins/updates

# 换源
[root@jenkins updates]# sed -i 's/https:\/\/updates.jenkins.io\/download/https:\/\/mirrors.tuna.tsinghua.edu.cn\/jenkins/g' /var/lib/jenkins/updates/default.json
[root@jenkins updates]# sed -i 's/http:\/\/www.google.com/https:\/\/www.baidu.com/g' /var/lib/jenkins/updates/default.json

# 安装插件并重启
[root@jenkins jenkins]# cd /var/lib/jenkins/plugins
[root@jenkins plugins]# wget http://106.13.81.75/plugins.tar.gz
[root@jenkins plugins]# tar -xf plugins.tar.gz
[root@jenkins plugins]# rm -rf plugins.tar.gz
[root@jenkins plugins]# systemctl restart jenkins

6.5 升级站点

jenkins --> 系统管理 --> 插件管理 --> 升级站点:https://mirrors.tuna.tsinghua.edu.cn/jenkins/updates/update-center.json

image-20220410221130162

image-20220410221028954

7、Jenkins 用户权限管理

我们可以使用 Role-based Authorization Strategy 插件,进行权限管理。

image.png

img

8、创建自由风格的项目

自由风格的项目是Jenkins中代码部署的常见的一个非常重要且定制性非常高的一个项目。

8.1 代码部署的流程

8.1.1 本地开发代码

img

8.1.2 提交代码托管服务器

image.png

8.1.4 创建凭证

image.png

image.png

image.png

image.png

image.png

image.png

8.1.5 关联主机

Jenkins关联部署的服务器。

image-20220410233745532

image.png

image-20220413111609585

image-20220413111653807

  • Jenkins服务器免密登录测试服务器

    [root@jenkins workspace]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.13.20
    

    image.png

    image-20220410234201104

    image-20220410234245013

img

image.png

image-20220410234857166

image-20220413112504199

8.2 编译型语言部署方式(java)

对于Jenkins来说,部署编译型语言和解释型语言之间最大的区别是,编译型语言需要编译。

8.2.1 配置maven环境

maven是用来编译java。

1、下载maven

[root@jenkins ~]# wget https://mirrors.aliyun.com/apache/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz

2、安装maven

[root@jenkins ~]# tar -xf apache-maven-3.6.3-bin.tar.gz  -C /usr/local/

image-20220413112705192

3、设置环境变量

[root@jenkins apache-maven-3.6.3]# vim /etc/profile  # 在末尾新增环境变量
export MAVEN_HOME=/usr/local/apache-maven-3.6.3
export PATH=$PATH:$MAVEN_HOME/bin

[root@jenkins apache-maven-3.6.3]# source /etc/profile

4、测试maven安装情况

[root@jenkins apache-maven-3.6.3]# mvn --version
Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
Maven home: /usr/local/apache-maven-3.6.3
Java version: 1.8.0_322, vendor: Red Hat, Inc., runtime: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.322.b06-1.el7_9.x86_64/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "3.10.0-1160.el7.x86_64", arch: "amd64", family: "unix"

8.2.2 Jenkins关联Java和maven4

1、设置jdk

image-20220410235936134

image-20220410235955918

image.png

2、设置maven目录

image.png

image-20220413113447339

image-20220413113500459

image-20220413113532386

image-20220413113729188

8.3 安装maven插件

# 升级jenkins版本
[root@jenkins jre-1.8.0-openjdk]# sudo wget -O /etc/yum.repos.d/jenkins.repo https://pkg.jenkins.io/redhat-stable/jenkins.repo
[root@jenkins jre-1.8.0-openjdk]# sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key
[root@jenkins jre-1.8.0-openjdk]# systemctl daemon-reload
[root@jenkins ~]# yum updata jenkins -y
[root@jenkins ~]# sed -i 's/https:\/\/updates.jenkins.io\/download/https:\/\/mirrors.tuna.tsinghua.edu.cn\/jenkins/g' /var/lib/jenkins/updates/default.json
[root@jenkins ~]# sed -i 's/https:\/\/updates.jenkins.io\/download/https:\/\/mirrors.tuna.tsinghua.edu.cn\/jenkins/g' /var/lib/jenkins/updates/default.json
[root@jenkins jre-1.8.0-openjdk]# systemctl start jenkins

image-20220411001739327

image.png

8.4 准备Java代码

在gitlab创建新项目--直接导库:https://gitee.com/chenyang0910/springboot.git

image.png

img

image-20220411004808862

image-20220413121509046

8.5 创建本地的maven仓库

maven在编译java代码时,需要下载很多的安装包,如果每一次去编译都去下载安装包会很浪费时间,因此,我们创建一个本地仓库用于下载下来的安装包,以至于下次构建无需再次下载。

8.5.1 创建本地仓库

[root@jenkins ~]# mkdir -pv /data/software/repository
mkdir: created directory ‘/data’
mkdir: created directory ‘/data/software’
mkdir: created directory ‘/data/software/repository’

[root@jenkins ~]# chown -R jenkins.jenkins /data

8.5.2 关联本地仓库

[root@jenkins ~]# vim /usr/local/apache-maven-3.6.3/conf/settings.xml  # 修改以下内容

  <localRepository>/data/software/repository/</localRepository>
  <mirrors>
     <mirror>
        <id>aliyunmaven</id>
        <mirrorOf>central</mirrorOf>
        <name>aliyun maven mirror</name>
        <url>https://maven.aliyun.com/repository/central</url>
     </mirror>
  </mirrors>

image-20220411005409323

8.6 配置maven编译java项目

image.png

image-20220413132815715

image.png

image-20220413134940662

image-20220413134915299

image-20220413135026662

image-20220411011024406

8.7 部署测试环境

一般情况下,我们代理java的服务叫作Tomcat。

8.7.1 安装Java

[root@localhost ~]# yum install java-1.8.0-openjdk* -y

image-20220413123819661

8.7.2 下载Tomcat

[root@localhost ~]# wget https://dlcdn.apache.org/tomcat/tomcat-9/v9.0.62/bin/apache-tomcat-9.0.62.tar.gz

8.7.3 配置Tomcat

[root@localhost ~]# tar -xf apache-tomcat-9.0.62.tar.gz -C /usr/local/

[root@localhost apache-tomcat-9.0.62]# vim /etc/profile  # 新增环境变量到最后
export TOMCAT_HOME=/usr/local/apache-tomcat-9.0.62
export PATH=$PATH:$TOMCAT_HOME/bin

[root@localhost apache-tomcat-9.0.62]# source /etc/profile

[root@localhost conf]# vim /usr/local/apache-tomcat-9.0.62/conf/tomcat-users.xml  # 新增在最后
<role rolename="tomcat"/>
<role rolename="role1"/>
<role rolename="manager-script"/>
<role rolename="manager-gui"/>
<role rolename="manager-status"/>
<role rolename="admin-gui"/>
<role rolename="admin-script"/>
<user username="tomcat" password="tomcat" roles="manager-gui,manager-script,tomcat,admin-gui,admin-script"/>

# 配置登录:注释掉只允许回环地址登录,因为需要jenkins登录
[root@localhost conf]# vim /usr/local/apache-tomcat-9.0.62/webapps/manager/META-INF/context.xml
  <!--<Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" /> -->

image-20220413124132334

8.7.4 启动Tomcat

[root@localhost apache-tomcat-9.0.62]# /usr/local/apache-tomcat-9.0.62/bin/startup.sh 
Using CATALINA_BASE:   /usr/local/apache-tomcat-9.0.62
Using CATALINA_HOME:   /usr/local/apache-tomcat-9.0.62
Using CATALINA_TMPDIR: /usr/local/apache-tomcat-9.0.62/temp
Using JRE_HOME:        /usr
Using CLASSPATH:       /usr/local/apache-tomcat-9.0.62/bin/bootstrap.jar:/usr/local/apache-tomcat-9.0.62/bin/tomcat-juli.jar
Using CATALINA_OPTS:   
Tomcat started.

[root@localhost ~]# netstat -nutlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      4262/nginx: master  
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1333/sshd           
tcp6       0      0 :::8080                 :::*                    LISTEN      4672/java           
tcp6       0      0 :::80                   :::*                    LISTEN      4262/nginx: master  
tcp6       0      0 :::22                   :::*                    LISTEN      1333/sshd           
tcp6       0      0 127.0.0.1:8005          :::*                    LISTEN      4672/java 

image-20220411012825342

image.png

8.8 配置Jenkins链接Tomcat

image-20220411013022171

image.png

image-20220411020327699

image-20220413125214105

image-20220411020505784

image-20220411014433212

image-20220411014656533

image-20220411020713250

image-20220413135438306

image-20220413135542594

image-20220413135559235

image-20220413135954448

image-20220413140035564

四、Jenkins参数化构建

Jenkins参数化构建是为了丰富Jenkins构建项目时的选择以及参数。

1、参数化构建

1.1 选项参数

可以设置成一个单选框。

image.png

image.png

1.2 文本参数

相当于需要一段文字

image.png

1.3 文件参数

img

1.4 布尔参数

image.png

1.5 密码参数

image.png

1.6 字符参数

img

1.7 凭据参数

image.png

1.8 级联参数

image.png

image.png

image.png

1.9 GIT参数

image.png

1.10 参数化构建java

image.png

image.png

image.png

image.png

image-20220413142256309

image-20220413142228732

2、构建触发器

通常有这样一种情况,就是代码一旦提交,就应该立即部署。

2.1 构建触发器的种类

  • 触发构建(代码一经提交,立即构建)
  • 其他工程构建,本工程立即构建
  • 定时构建
  • 轮询SCM构建

2.2 非触发构建

image-20220414063349472

image-20220414062935494

image-20220414062557891

image-20220414062808812

image-20220414062834307

image.png

image-20220414063013072

image-20220414062355625

image-20220414062411588

image-20220414062427900

image-20220414063732236

image-20220414063759094

image-20220414064525846

image-20220414064544007

2.3 触发构建(代码一经提交,立即构建)

image-20220414064838139

image-20220414064819263

image-20220414064931948

触发构建:触发远程构建

image-20220414065139666

image-20220414065603700

image-20220414065836046

image-20220414065924428

2.4 其他工程构建,本工程立即构建

image-20220414070450576

image-20220414070533146

image-20220414070851566

image-20220414070938569

2.5 定时构建

image-20220414071116681

2.6 轮询SCM构建

image-20220414072416792

2.7 webhook自动构建

image-20220414074643931

image-20220414074657934

image-20220414074747518

image-20220414073341736

image-20220414072651353

image-20220414072818417

image-20220414072840017

image-20220414074226425

image-20220414074829931

image-20220414074914107

image-20220414075746713

五、流水线

流水线是通过代码的方式编写构建的步骤。流水线最大的好处就是可以复用。

1、安装流水线插件

image-20220414080106492

image-20220414080120292

image-20220414080200340

2、创建流水线项目

image-20220414081155494

image-20220414082409699

3、流水线语法

pipeline {
  agent any
  stages {
    stage('pull code') {
      parallel {
        stage('pull code') {
          steps {
            sleep 10
          }
        }

        stage('check env') {
          steps {
            sleep 10
          }
        }
      }
    }
  }
}

# 语法中的名词解释:
pipeline	: 代表一条流水线,每一个流水线项目有且只有一个pipeline
agent		: 代表这条流水线将在什么环境下运行(eg:docker、kubernetes、any-代表在任何环境下运行)
parallel  	: 并行操作
stages		: 代表整个流水线的所有执行阶段
stage		: 代表流实现中的某一个阶段
steps		: 代表某一个阶段中的具体步骤


# 示例(注意涉及变量的时候需要换成双引号,不能用单引号):
pipeline {
    agent any
    stages {
        stage ('拉取代码') {
            steps {
                git branch: 'main', credentialsId: 'e0b54b36-1cd9-488b-94d6-46b6f518857d', url: 'git@124.220.41.46:wotiecity/html.git'
            }
        }
        stage ('切换分支') {
            steps {
                sh """#!/bin/bash
                echo "切换分支"
			   git checkout $GET_TAG"""
            }    
        }
        
        stage ('部署代码') {
            steps {  
                sshPublisher(publishers: [sshPublisherDesc(configName: '测试服务器', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: '''#!/bin/bash
echo "部署完成"''', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '', remoteDirectorySDF: false, removePrefix: '', sourceFiles: '**/**')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)]) 
            }
        }
    }
}

image-20220415144827560

image-20220415145023018

image-20220415145106950

image-20220415145206398

image-20220415145339850

image-20220415145540618

image-20220415155331288

image-20220415175938870

4、自动创建流水线

image-20220415150904984

image-20220415150927617

image-20220415145730046

image-20220415145801888

image-20220415145844418

image-20220415150021182

image-20220415150451315

image-20220415150545956

image-20220415211439595

image-20220415224525632

image-20220415224619674

image-20220415231800669

image-20220415234551014

image-20220416012453630

pipeline {
  agent any
  stages {
    stage('环境初始化和拉取代码') {
      parallel {
        stage('拉取代码') {
          steps {
            git credentialsId: '55fd0710-3451-4045-be7d-1c36a5a5b2a0', url: 'git@106.52.17.244:group/springboot.git'
          }
        }

        stage('环境初始化') {
          steps {
            sh """
                echo "初始化环境"
                sleep 10

            """
          }
        }

      }
    }

    stage('切换分支') {
      steps {
        sh """#!/bin/bash

            git checkout $GIT_TAG"""
      }
    }

    stage('检查代码') {
      steps {
        sh """
            echo "检查代码"
            sleep 10

            """
      }
    }

    stage('编译代码') {
      steps {
        sh '''#!/bin/bash

            echo "编译代码"
            mvn clean package '''
      }
    }

    stage('部署到Tomcat') {
      steps {
        deploy adapters: [tomcat9(credentialsId: 'bffab838-3538-4457-917a-26e89f3a7a3e', path: '', url: 'http://106.55.254.107:80/')], contextPath: null, war: 'target/*.war'
      }
    }

    stage('发送邮件给管理员') {
      steps {
        sleep 10
      }
    }
  }
}

5、发送邮件

image-20220416012537219

image.png

image-20220416012959428

image-20220416012912587

image-20220416013015526

image.png

image-20220416015146089

image-20220416015438981

image-20220416015833330

pipeline {
  agent any
  stages {
    stage('环境初始化和拉取代码') {
      parallel {
        stage('拉取代码') {
          steps {
            git credentialsId: 'e0b54b36-1cd9-488b-94d6-46b6f518857d', url: 'git@106.52.17.244:group/springboot.git'
          }
        }

        stage('环境初始化') {
          steps {
            sh """
                echo "初始化环境"
                sleep 10
            """
          }
        }

      }
    }

    stage('切换分支') {
      steps {
        sh """#!/bin/bash
		git checkout $GET_TAG"""
      }
    }

    stage('检查代码') {
      steps {
        sh """
            echo "检查代码"
            sleep 10

            """
      }
    }

    stage('编译代码') {
      steps {
        sh '''#!/bin/bash
			echo "编译代码"

mvn clean package '''
      }
    }

    stage('部署到Tomcat') {
      steps {
        deploy adapters: [tomcat9(credentialsId: '097807bb-f062-49d8-8d1b-7f9d8e6017de', path: '', url: 'http://106.55.254.107:8080/')], contextPath: null, war: 'target/*.war'
      }
    }
  }

  post {
    always {
      
      emailext body: '''
      <!DOCTYPE html><html><head><meta charset="UTF-8"><title>${ENV,var="JOB_NAME"}-第${BUILD_NUMBER}次构建日志</title></head><body leftmargin="8"marginwidth="0"topmargin="8"marginheight="4"offset="0"><table width="95%"cellpadding="0"cellspacing="0"style="font-size: 11pt; font-family: Tahoma, Arial, Helvetica, sans- serif"><tr><td>(本邮件是程序自动下发的,请勿回复!)</td></tr><tr><td><h2><font color="#0000FF">构建结果-${BUILD_STATUS}</font></h2></td></tr><tr><td><br/><b><font color="#0B610B">构建信息</font></b><hr size="2"width="100%"align="center"/></td></tr><tr><td><ul><li>项目名称&nbsp;:&nbsp;${PROJECT_NAME}</li><li>构建编号&nbsp;:&nbsp;第${BUILD_NUMBER}次构建</li><li>触发原因:&nbsp;${CAUSE}</li><li>构建日志:&nbsp;<a href="${BUILD_URL}console">${BUILD_URL}console</a></li><li>构建&nbsp;&nbsp;Url&nbsp;:&nbsp;<a href="${BUILD_URL}">${BUILD_URL}</a></li><li>工作目录&nbsp;:&nbsp;<a href="${PROJECT_URL}ws">${PROJECT_URL}ws</a></li><li>项目&nbsp;&nbsp;Url&nbsp;:&nbsp;<a href="${PROJECT_URL}">${PROJECT_URL}</a></li></ul></td></tr><tr><td><b><font color="#0B610B">Changes Since Last Successful Build:</font></b><hr size="2"width="100%"align="center"/></td></tr>编写Jenkinsfile添加构建后发送邮件<tr><td><ul><li>历史变更记录:<a href="${PROJECT_URL}changes">${PROJECT_URL}changes</a></li></ul>${CHANGES_SINCE_LAST_SUCCESS,reverse=true,format="Changes for Build#%n: <br />%c <br />",showPaths=true,changesFormat=" <pre>[%a]<br />%m</pre>",pathFormat="&nbsp;&nbsp;&nbsp;&nbsp;%p"}</td></tr><tr><td><b>Failed Test Results</b><hr size="2"width="100%"align="center"/></td></tr><tr><td><prestyle="font-size: 11pt; font-family: Tahoma, Arial, Helvetica, sans-serif">$FAILED_TESTS</pre><br/></td></tr><tr><td><b><font color="#0B610B">构建日志(最后100行):</font></b><hr size="2"width="100%"align="center"/></td></tr><tr><td><textarea cols="80"rows="30"readonly="readonly"style="font-family: Courier New">${BUILD_LOG,maxLines=100}</textarea></td></tr></table></body></html>
      ''', subject: '【构建通知】${ENV, var="JOB_NAME"}-第${BUILD_NUMBER}次构建日志', to: 'qinqiuling0515@163.com'

    }
  }
}

六、SonarQube(代码检查)

SonarQube是一个用于管理代码质量的开发平台,可以快速的定位代码中潜在的或者明显的错误。

目前 SonarQube 已经支持了Java、C#、C、C++、Python、PHP、SQL、Golang已经Javascript等多种语言的检查功能。

官网:https://www.sonarqube.org/

1、部署SonarQube的要求

软件 版本
SonarQube 6.7以上
MySQL 5.7
JDK 1.8

2、下载软件

wget http://106.13.81.75/sonarqube.zip
yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
yum makecache fast
yum install docker-ce-19.03.12 -y
systemctl start docker

3、安装SonarQube

# 安装JDK
[root@VM-0-2-centos ~]# yum install java-1.8.0-openjdk* -y

# 安装数据库
[root@VM-0-2-centos ~]# docker run -d --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 mysql:5.7

# 授权
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'  IDENTIFIED BY '123456'  WITH GRANT OPTION;

mysql> flush privileges;

# 创建SonarQube的数据库
mysql> create database SonarQube;
Query OK, 1 row affected (0.00 sec)

# 安装SonarQube
[root@VM-0-2-centos ~]# unzip sonarqube.zip

[root@VM-0-2-centos ~]# mv sonarqube-6.7.4 /usr/local/

[root@VM-0-2-centos sonarqube-6.7.4]# vim /etc/profile
export SonarQube_HOME=/usr/local/sonarqube-6.7.4
export PATH=$PATH:$SonarQube_HOME/bin

[root@VM-0-2-centos sonarqube-6.7.4]# source /etc/profile

# 创建用户
[root@VM-0-2-centos sonarqube-6.7.4]# useradd sonar

# 给用户授权
[root@VM-0-2-centos sonarqube-6.7.4]# chown -R sonar.sonar /usr/local/sonarqube-6.7.4


# 修改SonarQube的配置
[root@VM-0-2-centos sonarqube-6.7.4]# vim /usr/local/sonarqube-6.7.4/conf/sonar.properties 
sonar.jdbc.username=root
sonar.jdbc.password=123456
sonar.jdbc.url=jdbc:mysql://192.168.0.2:3306/SonarQube?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance&useSSL=false

# 修改内核参数
[root@VM-0-2-centos sonarqube-6.7.4]# vim /etc/sysctl.conf
vm.max_map_count=655360
[root@VM-0-2-centos sonarqube-6.7.4]# sysctl -p

# 启动SonarQube
[root@VM-0-2-centos sonarqube-6.7.4]# su sonar /usr/local/sonarqube-6.7.4/bin/linux-x86-64/sonar.sh start 
Starting SonarQube...
Started SonarQube.

# 查看SonarQube的启动状告
[root@VM-0-2-centos ~]# su sonar /usr/local/sonarqube-6.7.4/bin/linux-x86-64/sonar.sh status
SonarQube is running (1951).

image.png

image.png

image.png

904eda2c1c46dbe4d0a9e0ea37f233c7201dfe81

mvn sonar:sonar \

-Dsonar.host.url=http://124.220.33.31:9000 \

-Dsonar.login=904eda2c1c46dbe4d0a9e0ea37f233c7201dfe81

image.png

image.png

image.png

image.png

image.png

image.png

# must be unique in a given SonarQube instance
sonar.projectKey=wotie_java

# this is the name displayed in the SonarQube UI
sonar.projectName=wotie_java
#sonar.language=java
sonar.projectVersion=1.0

# the sonar-project.properties file.
sonar.sources=.

# 排除某些文件不检查
sonar.exclusions=**/test/**,**/target/**

# 设置JDK版本号
sonar.java.source=1.8
sonar.java.target=1.8

# 设置字符集编码
sonar.sourceEncoding=UTF-8

image.png

pipeline {
  agent any
  stages {
    stage('环境初始化和拉取代码') {
      parallel {
        stage('拉取代码') {
          steps {
            git credentialsId: 'e0b54b36-1cd9-488b-94d6-46b6f518857d', url: 'git@124.222.165.136:wotiecity/springboot.git'
          }
        }

        stage('环境初始化') {
          steps {
            sh """

                echo "初始化环境"

                sleep 10

            """
          }
        }

      }
    }

    stage('切换分支') {
      steps {
        sh """#!/bin/bash

git checkout $GET_TAG"""
      }
    }

    stage('SonarQube代码审查') {
      steps {
        script {
          scannerHome = tool 'SonarQube-scanner'
        }
        withSonarQubeEnv('SonarQube6.4.7') {
          sh "${scannerHome}/bin/sonar-scanner"
        }
      }
    }

    stage('编译代码') {
      steps {
        sh '''#!/bin/bash

echo "编译代码"

mvn clean package '''
      }
    }

    stage('部署到Tomcat') {
      steps {
        deploy adapters: [tomcat9(credentialsId: '097807bb-f062-49d8-8d1b-7f9d8e6017de', path: '', url: 'http://121.4.208.149:8080/')], contextPath: null, war: 'target/*.war'
      }
    }
  }

  post {
    always {
      
      emailext body: '''
      <!DOCTYPE html><html><head><meta charset="UTF-8"><title>${ENV,var="JOB_NAME"}-第${BUILD_NUMBER}次构建日志</title></head><body leftmargin="8"marginwidth="0"topmargin="8"marginheight="4"offset="0"><table width="95%"cellpadding="0"cellspacing="0"style="font-size: 11pt; font-family: Tahoma, Arial, Helvetica, sans- serif"><tr><td>(本邮件是程序自动下发的,请勿回复!)</td></tr><tr><td><h2><font color="#0000FF">构建结果-${BUILD_STATUS}</font></h2></td></tr><tr><td><br/><b><font color="#0B610B">构建信息</font></b><hr size="2"width="100%"align="center"/></td></tr><tr><td><ul><li>项目名称&nbsp;:&nbsp;${PROJECT_NAME}</li><li>构建编号&nbsp;:&nbsp;第${BUILD_NUMBER}次构建</li><li>触发原因:&nbsp;${CAUSE}</li><li>构建日志:&nbsp;<a href="${BUILD_URL}console">${BUILD_URL}console</a></li><li>构建&nbsp;&nbsp;Url&nbsp;:&nbsp;<a href="${BUILD_URL}">${BUILD_URL}</a></li><li>工作目录&nbsp;:&nbsp;<a href="${PROJECT_URL}ws">${PROJECT_URL}ws</a></li><li>项目&nbsp;&nbsp;Url&nbsp;:&nbsp;<a href="${PROJECT_URL}">${PROJECT_URL}</a></li></ul></td></tr><tr><td><b><font color="#0B610B">Changes Since Last Successful Build:</font></b><hr size="2"width="100%"align="center"/></td></tr>编写Jenkinsfile添加构建后发送邮件<tr><td><ul><li>历史变更记录:<a href="${PROJECT_URL}changes">${PROJECT_URL}changes</a></li></ul>${CHANGES_SINCE_LAST_SUCCESS,reverse=true,format="Changes for Build#%n: <br />%c <br />",showPaths=true,changesFormat=" <pre>[%a]<br />%m</pre>",pathFormat="&nbsp;&nbsp;&nbsp;&nbsp;%p"}</td></tr><tr><td><b>Failed Test Results</b><hr size="2"width="100%"align="center"/></td></tr><tr><td><prestyle="font-size: 11pt; font-family: Tahoma, Arial, Helvetica, sans-serif">$FAILED_TESTS</pre><br/></td></tr><tr><td><b><font color="#0B610B">构建日志(最后100行):</font></b><hr size="2"width="100%"align="center"/></td></tr><tr><td><textarea cols="80"rows="30"readonly="readonly"style="font-family: Courier New">${BUILD_LOG,maxLines=100}</textarea></td></tr></table></body></html>
      ''', subject: '【构建通知】${ENV, var="JOB_NAME"}-第${BUILD_NUMBER}次构建日志', to: 'chenyangqit@163.com'

    }
  }
}
posted @ 2022-04-16 16:57  90啊  阅读(511)  评论(1编辑  收藏  举报